最近公司要跨域请求一个服务,服务未启动的时候还要报错。自己做了一个以符合业务需求
贴上源码:
希望大家能多多提意见
/**
- v 1.0
- author xingzheng
- date 2018-12-19
*/
var JSONP = {
now : function() {
return (new Date()).getTime();
},
rand : function() {
return Math.random().toString().substr(2);
},
waitPostArr:[],
currentNodeName: "",
removeElem : function(elem) {
try{
var parent = elem.parentNode;
if (parent && parent.nodeType !== 11) {
parent.removeChild(elem);
}
}catch(e){
console.log(e);
}
},
parseData : function(data) {
var ret = "";
if (typeof data === "string") {
ret = data;
} else if (typeof data === "object") {
for ( var key in data) {
ret += "&" + key + "=" + encodeURIComponent(data[key]);
}
}
ret += "&_time=" + this.now();
ret = ret.substr(1);
return ret;
},
getJSONS : function(arr){
this.waitPostArr = arr;
this.getJSON(arr[0].url, arr[0].data, arr[0].func);
this.waitPostArr.splice(0, 1);
},
getJSON : function(url, data, func) {
var name;
if(url.url){
url = url + (url.url.indexOf("?") === -1 ? "?" : "&")
+ this.parseData(data);
}else{
url = url + (url.indexOf("?") === -1 ? "?" : "&")
+ this.parseData(data);
}
var match = /callback=(\w+)/.exec(url);
if (match && match[1]) {
name = match[1];
} else {
name = "jsonp_" + this.now() + '_' + this.rand();
url = url.replace("callback=?", "callback=" + name);
url = url.replace("callback=%3F", "callback=" + name);
}
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
script.id = "id_" + name;
script.onerror = function() {
try{
func({
result : "connectFailed"
});
}catch(e){
JSONP.JSONP_next();
}
};
var head = document.getElementsByTagName("head");
if (head && head[0]) {
head[0].appendChild(script);
}
this.currentNodeName = name;
},
JSONP_next : function(){
if(this.waitPostArr && this.waitPostArr.length > 0){
this.getJSON(this.waitPostArr[0].url, this.waitPostArr[0].data, this.waitPostArr[0].func);
this.waitPostArr.splice(0, 1);
}
}
};
window["success_jsonpCallback"] = function(json) {
var elem = document.getElementById("id_" + JSONP.currentNodeName);
JSONP.removeElem(elem);
try{
func(json);
JSONP.JSONP_next();
}catch(e){
JSONP.JSONP_next()
}
};
给windows赋函数的时候没有采取一个请求一个函数是因为后台服务参数没有函数名称(WTF)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。