-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
61 lines (59 loc) · 1.37 KB
/
index.js
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
const jsonp = ({
url = '',
params = {},
timeout = 6000,
callback = 'jsonpCallback'
}) => {
//拼接url
if (url.indexOf('?') !== -1) {
url = url + '&';
} else {
url = url + '?';
}
let paramsToString = '';
for (let key in params) {
paramsToString += `&${key}=${encodeURIComponent(params[key])}`;
}
paramsToString = paramsToString.slice(1);
url += paramsToString;
callback = callback + String(new Date().getTime());
url += `&callback=${callback}`;
//url处理结束
let timer; //timeout处理
const script = document.createElement('script');
script.src = url;
function cleanup() {
timer && clearTimeout(timer);
document.head.removeChild(script);
window[callback] = undefined;
}
return new Promise((resolve, reject) => {
//timeout处理
if (timeout) {
timer = setTimeout(() => {
reject({
message: '请求超时',
type: 'error'
});
cleanup();
}, timeout);
}
//error处理
script.onerror = (e) => {
reject({
message: '请检查url是否拼写正确或后端有无配置jsonp响应',
type: 'error'
});
cleanup();
}
//正常处理
window[callback] = (data) => {
resolve(data);
cleanup();
};
// 发起请求
document.head.appendChild(script);
//发起请求结束
});
};
export default jsonp;