一直未曾注意,jquery在跨域ajax的时候,是不进行异常处理的.
如:
$.ajax({url:'http://www.testn.com',
success:function(){},
error:function(){console.log('error')},
dateType:'jsonp'},);
此处目标网站如果是404或者500错误的时候,error方法是不能感知的.
见api文档说明:
error(jqXHR, textStatus, errorThrown)Function
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null
) are "timeout"
, "error"
, "abort"
, and "parsererror"
. When an HTTP error occurs, errorThrown
receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error
setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.
参考页面加载script的方法.做个异常处理.
jQuery.extend({
getJSONByScript : function(url, jsonpCallName, success, error){
var js = document.createElement("script");
js.src = url;
js.onload = js.onreadystatechange = function () {
if (js.readyState && js.readyState != "loaded" && js.readyState != "complete") {
return;
}
js.onload = js.onreadystatechange = js.onerror = null;
js.src = "";
js.parentNode.removeChild(js);
js = null;
try{success && success($.jsonp[jsonpCallName])}catch(e){error && error();};
delete $.jsonp[jsonpCallName];
};
js.onerror = function () {
js.onload = js.onreadystatechange = js.onerror = null;
js.src = "";
js.parentNode.removeChild(js);
js = null;
error && error();
delete $.jsonp[jsonpCallName];
};
document.getElementsByTagName("head")[0].appendChild(js);
},
extendJsonp : function(url,success,error,callbackStr){//callbackStr为jsonpCallback参数.
$.jsonp = $.jsonp || {};
var tmpParam = 'jsonp_'+new Date().getTime();
$.getJSONByScript(url + '&'+(callbackStr?callbackStr:'jsoncallback')+'=$.jsonp.'+tmpParam+'=',tmpParam,success,error);
}
});
function test(){
var URL = 'http://testurl?param=n';
$.extendJsonp(URL,function(data){console.log('success');},function(){alert('error')});
}
未完成部分
1 以前的地址为http://test.com/getContext?callback=?
现在需要去掉callback参数.(即$.extendJsonp('http://test.com/getContext?',...))方法自动填充.
最后请求地址为http://test.com/getContext?&callback=$.jsonp.jsonp_13422345523这样的形式.描红部分未处理.总是多传送一个字符.不优雅.