jquery 跨域ajax中的异常处理

一直未曾注意,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这样的形式.描红部分未处理.总是多传送一个字符.不优雅.


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值