jsonp.js
1.67 KB
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
var Promise = require('./promise');
// jsonp请求
function jsonp(params) {
return new Promise(function (resovle, reject) {
params = params || {};
params.data = params.data || {};
//创建script标签并加入到页面中
var callbackName = params.jsonp;
if (window[callbackName]) {
callbackName += Math.floor(Math.random() * 1000);
params.jsonp = callbackName;
}
// 设置传递给后台的回调参数名
params.data['callback'] = callbackName;
var data = formatParams(params.data);
var script = document.createElement('script');
document.body.appendChild(script);
// 创建jsonp回调函数
window[callbackName] = function (json) {
document.body.removeChild(script);
clearTimeout(script.timer);
window[callbackName] = null;
return resovle(json);
};
// 发送请求
script.src = params.url + '?' + data;
//为了得知此次请求是否成功,设置超时处理
if (params.timeout) {
script.timer = setTimeout(function () {
window[callbackName] = null;
document.body.removeChild(script);
reject({message: '超时'});
}, params.timeout);
}
})
}
//格式化参数
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
// 添加一个随机数,防止缓存
var date = new Date();
arr.push('v=' + date.getTime());
return arr.join('&');
}
module.exports = jsonp;