jsonp实现一个简单的类似百度提示的功能

众所周知,由于所有支持JavaScript的浏览器都会采用同源策略,Ajax直接请求普通文件存在跨域无权限访问的问题。
而 HTML的 script 元素是一个例外。利用 script元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 jsonp。
话不多说,现在用一个小例子来实现jsonp的小功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jsonp.js"></script>
<script>
function json2url(json){
var arr = [];
for(var name in json){
arr.push(name+'='+encodeURIComponent(json[name]));
}
return arr.join('&');
}
//url,data,timeout,success,error
function jsonp(options){
options = options||{};
options.data = options.data||{};
options.timeout = options.timeout||0;

//创建全局函数
options.data.cb = 'jsonp_'+Math.random();
options.data.cb = options.data.cb.replace('.','');
window[options.data.cb] = function(json){
options.success&&options.success(json);
document.head.removeChild(oS);
};
//插入标签
var oS = document.createElement('script');
oS.src = options.url+'?'+json2url(options.data);
document.head.appendChild(oS);
var timer = null;
if(options.timeout){
clearTimeout(timer);
setTimeout(function(){
window[options.data.cb] = null;
options.error&&options.error();

},options.timeout);
}
}
window.onload = function(){
var oTxt = document.getElementById('txt');
var oUl = document.getElementById('ul1');
oTxt.onkeyup = function(){
jsonp({
url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
data:{
wd:oTxt.value
},
success:function(json){
var arr= json.s;
console.log(json);
oUl.innerHTML='';
for(var i = 0;i<arr.length;i++){
var oLi = document.createElement('li');
oLi.innerHTML = arr[i];
oUl.appendChild(oLi);
}
},
error:function(){
alert('error! request timeout');
}

});
};

};
</script>
</head>
<body>
<input type="text" id="txt">
<ul id="ul1"></ul>
</body>
</html>