-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonp.js
53 lines (52 loc) · 1.76 KB
/
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
52
53
;(function () {
/**
* JSONP操作
* @param url : request url
* @param data : send data
* @param jsonpcallback : 服务器给出的JSONP端口的API名称
* @param callback : 执行JSONP获取数据的回调函数
*/
var jsonp = function (url, data, jsonpcallback, callback) {
var cbName = 'cb' + jsonp.count++;
var callbackName = 'window.jsonp.' + cbName;
window.jsonp[cbName] = function (jsonpData) {
try {
callback(jsonpData);
} finally {
script.parentNode.removeChild(script);
delete window.jsonp[cbName];
}
};
var script = document.createElement('script');
if (data) {
data = tool.encodeToURIString(data);
}
if (typeof jsonpcallback === 'string') {
var jsonpData = jsonpcallback + '=' + callbackName;
}
url = tool.hasSearch(url, data);
url = tool.hasSearch(url, jsonpData);
script.src = url;
document.body.appendChild(script);
};
jsonp.count = 0;
window.jsonp = jsonp;
var tool = {
encodeToURIString: function (data) {
if (!data) return '';
if (typeof data === 'string') return data;
var arr = [];
for (var n in data) {
if (!data.hasOwnProperty(n)) continue;
arr.push(encodeURIComponent(n) + '=' + encodeURIComponent(data[n]));
}
return arr.join('&');
},
hasSearch: function (url, padString) {
if (!padString) return url;
if (typeof padString !== 'string') return url;
return url + (/\?/.test(url) ? '&' : '?') + padString;
}
}
})();
module.exports = jsonp;