-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3. jsonp.js
51 lines (47 loc) · 1.27 KB
/
3. jsonp.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
/**
* jsonp
* @param {*} url
* @param {*} data
* @returns
*/
function jsonp(url, data = {}) {
return new Promise((resolve, reject) => {
const callbackName = `jsonp_${Math.random()
.toString(36)
.slice(2)}_${new Date().getTime()}`;
// 获取url
const getUrl = () => {
const params = Object.keys(data).map(
(key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
);
return `${url}?${params.join('&')}&callback=${callbackName}`;
};
// 回调函数
window[callbackName] = (data) => {
try {
resolve(data);
} catch (error) {
reject(error);
}
// 移除
removeScriptAndCallback(callbackName);
};
// 添加script
const script = document.createElement('script');
script.onerror = () => {
reject(new Error('Script load error'));
removeScriptAndCallback(callbackName);
};
script.src = getUrl();
document.body.appendChild(script);
// 移除script和回调函数的工具函数
function removeScriptAndCallback(callbackName) {
if (script && script.parentNode) {
document.body.removeChild(script);
}
if (typeof window[callbackName] === 'function') {
delete window[callbackName];
}
}
});
}