怎么捕获JSONP跨域请求的连接异常? 400 报错
代码如下:
function jsonpTest(){
var JSONP = document.createElement("script");}
function callback(){}
问题:如果跨域请求异常,怎么捕获到。我知道jQuery封装的JSONP可以解决,特殊原因我这里不能用jQuery.在线等!
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
捕获不了的,只有用超时实现。jquery对跨域jsonp请求是没有做异常处理的。
######你回调了callback,,这个callback可以写成一个包含闭包,或者是某个可见变量的函数,,,,然后在其他你要调用那块json的时候,通过判断前面进去的闭包或者其他变量值,,,来判断这个script的加载情况######能给个demo吗,js研究不是很深入.######仅供参考 —— http://blog.csdn.net/qingralf/article/details/8285048######windows.error 不是这个? ######
var JSONP = (function () {
var counter = 0,
head, query, key, window = this;
function load(url) {
var script = document.createElement('script'),
var done = false;
script.src = url;
script.async = true;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
done = true;
script.onload = script.onreadystatechange = null;
if (script && script.parentNode) {
script.parentNode.removeChild(script);
}
}
};
if (!head) {
head = document.getElementsByTagName('head')[0];
}
head.appendChild(script);
}
function jsonp(url, params, error, callback) {
query = "?";
params = params || {};
for (key in params) {
if (params.hasOwnProperty(key)) {
query += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
}
}
var jsonp = "json" + (++counter);
window[jsonp] = function (data) {
callback(data);
try {
delete window[jsonp];
} catch (e) {}
window[jsonp] = null;
};
load(url + query + "callback=" + jsonp);
error = error ||
function () {};
window.setTimeout(function () {
if (typeof window[jsonp] == "function") {
// replace success with null callback in case the request is just very latent.
window[jsonp] = function (data) {
try {
delete window[jsonp];
} catch (e) {}
window[jsonp] = null;
};
// call the error callback
error();
// set a longer timeout to safely clean up the unused callback.
window.setTimeout(function () {
if (typeof window[jsonp] == "function") {
try {
delete window[jsonp];
} catch (e) {}
window[jsonp] = null;
};
}, 120000);
};
}, 10000);
return jsonp;
}
return {
get: jsonp
};
}());
/*
Example:
----------------
var url = 'http://blog.eood.cn/api';
var error = function() {alert('error');};
var success = function(data) {
// process the data
};
JSONP.get( url, {'parm1': 'parm1_value', 'parm2': 'parm2_value'}, error, success);
*/
找到一个JSONP的封装,原理还是利用超时,结贴!
$.ajaxSetup( {
error: function(jqXHR, textStatus, errorMsg){ // 出错时默认的处理函数
// jqXHR 是经过jQuery封装的XMLHttpRequest对象
// textStatus 可能为: null、"timeout"、"error"、"abort"或"parsererror"
// errorMsg 可能为: "Not Found"、"Internal Server Error"等
// 提示形如:发送AJAX请求到"/index.html"时出错[404]:Not Found
alert( '发送AJAX请求到"' + this.url + '"时出错[' + jqXHR.status + ']:' + errorMsg );
}
} );