模仿jsonp跨域请求
发布时间:2020-12-16 18:59:36 所属栏目:百科 来源:网络整理
导读:var jsonp = function() { var extend = function(obj,attrs) { for (var name in attrs) { obj[name] = attrs[name]; } }; var jsonp = function() { jsonp_imp.apply(null,arguments); }; extend(jsonp,{ guid: 0,requests: {},avail_tag: [],request_time
var jsonp = function() {
var extend = function(obj,attrs) {
for (var name in attrs) {
obj[name] = attrs[name];
}
};
var jsonp = function() {
jsonp_imp.apply(null,arguments);
};
extend(jsonp,{
guid: 0,requests: {},avail_tag: [],request_timeout: 5 //seconds
});
var Request = function(obj) {
extend(this,obj);
this.init && this.init();
};
var oo = Request.prototype;
oo.remove = function() {
var js = this.js;
js.parentNode.removeChild(js);
js = null;
delete jsonp.requests[this.id];
};
oo.on_complete = function() {
if (this.success) {
this.success();
this.success = null;
}
};
oo.on_timeout = function() {
var state = this.js.readyState;
if (state != 'complete' && state != 'loaded' && this.failed) {
this.failed();
this.failed = null;
}
state = null;
this.remove();
};
oo.init = function() {
var request = this;
this.js.onload = function() {
request.on_complete();
};
setTimeout(function() {
request.on_timeout();
},request.timeout);
};
var jsonp_imp = function(url,charset,timeout,failed,success) {
var head = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
head.appendChild(js);
if (!charset) {
charset = 'utf-8';
}
var id = jsonp.guid++;
if (!timeout) {
timeout = jsonp.request_timeout * 1000;
}
var now = new Date();
var request = new Request({
id: id,url: url,charset: charset,failed: failed,success: success,js: js,stat_time: now,timeout: timeout
});
jsonp.requests[id] = request;
js.charset = charset;
js.src = url;
return id;
};
return jsonp;
}();
var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js";
var url2 = "http://saic-sis.escdn.com/api.php?op=get_linkage_xjw&parentid=10000000000004&act=ajax_getlist&keyid=1&callback=cb";
jsonp(url2,null,5000,function(){alert("failed");},function(){alert("load ok");}
);
function cb(d) {
console.log(d);
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
