-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs-JSONP
More file actions
59 lines (53 loc) · 1.97 KB
/
js-JSONP
File metadata and controls
59 lines (53 loc) · 1.97 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 jsonpCallback =function(option){alert(option)}
jsonp({
url: "http://10.17.1.87:8889/userAuthorization/query.htm", //请求地址
type: "GET", //请求方式
data: {userName: "wangwenjie1",callback:"jsonpCallback"}, //请求参数
dataType: "jsonp",
jsonp: "callback",
callback:"jsonpCallback",
success: function (response, xml) {
alert('成功')
},
fail: function (status) {
alert('失败')
}
});
function jsonp(options) {
options = options || {};
if (!options.url || !options.callback) {
throw new Error("参数不合法");
}
//创建 script 标签并加入到页面中
var callbackName = ('jsonp_' + Math.random()).replace(".", "");
var oHead = document.getElementsByTagName('head')[0];
options.data[options.callback] = callbackName;
var params = formatParams(options.data);
var oS = document.createElement('script');
oHead.appendChild(oS);
//创建jsonp回调函数
window[callbackName] = function (json) {
oHead.removeChild(oS);
clearTimeout(oS.timer);
window[callbackName] = null;
options.success && options.success(json);
};
//发送请求
oS.src = options.url + '?' + params;
//超时处理
if (options.time) {
oS.timer = setTimeout(function () {
window[callbackName] = null;
oHead.removeChild(oS);
options.fail && options.fail({ message: "超时" });
}, time);
}
};
//格式化参数
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
return arr.join('&');
}