ajax

环境
jquery 1.3.2 vs2005 windows server 2003
需求:我想用jquery写一个通用地处理ajax响应异常的方式(因为大多情况下ajax响应报错程序总是看不到详细信息)于是研究ajax的有关机制

2.要想使用ajaxError(function(e,xhr,o)统一处理错误代码是很难的,不准确的,以下情况
一.异常:服务器端new Exception("aaa"); 取错误状态码$(xhr).attr("status")会得到500错误代码
二.超时:$.ajax({timeout:1,//设置超时 服务器端System.Threading.Thread.Sleep(30000);强制超时
error:function(data,stateMsg){
alert("error:"+stateMsg);//但这里的状态码却能正常显示
}
} });//再ajaxError(function(e,xhr,o)执行$(xhr).attr("status")那就完了js代码出错,整个和程序崩溃
三.服务器主动断开:如果服务器 Response.Close();那么ajax在IE和firefox两种情况;IE会触发ajaxError(function(e,xhr,o)不会触发success事件;而firefox相反不会触发ajaxError(function(e,xhr,o)反而认为成功.一般地请求被服务器主动断开应该算错误

4.解析对象错误。
jQuery ajax返回parsererror错误的解决方法


[javascript] view plaincopyprint?
01.function delAttach(id)
02.{
03. if(confirm("删除附件会连同对应的文件一起删除,确认删除吗?"))
04. {
05. $('#attachSpan_'+id).html("<img src='__PUBLIC__/Images/loading.gif' />");
06. //使用ajax先去把附件表里面的数据删除,再来把页面上的div删除
07.
08. //alert('__APP__/Attach/delAttach');
09. $.ajax({
10. type: "POST",
11. url: "__APP__/Attach/delAttach",
12. data: 'ajax=1&id='+id,
13. dataType: "json",
14. success: function(response){
15. if(response.status == 1)
16. {
17. //alert('执行到这里!');
18. $("div").remove("#attach_"+id);
19.
20. }
21. else
22. $('#attachSpan_'+id).html(response.info);
23.
24. },
25. error: function(XmlHttpRequest,textStatus,errorThrown){
26. var $errorPage = XmlHttpRequest.responseText;
27. alert($($errorPage).text());
28. }
29. });
30. //alert('执行到这里!');
31. }
32.}


对jQuery来说,超时可以直接设置timeout参数,并在error事件中捕获第二个参数,如果是“timeout”则表明捕获了超时事件,非常清楚。
要设置请求超时可以用全局属性$.ajaxSetup({timeout:5000});

例子:

$.ajax({ type: "POST", contentType: "application/json", url: "../ws/MyService.asmx/test", data: '{"email":"'+email+'"}', timeout: 30000, //超时时间:30秒
dataType: 'json', error: function(XMLHttpRequest, textStatus, errorThrown){ //TODO: 处理status, http status code,超时 408
// 注意:如果发生了错误,错误信息(第二个参数)除了得到null之外,还可能
//是"timeout", "error", "notmodified" 和 "parsererror"。
},
success: function(result) { // TODO: check result
}
});
参考的这个http://www.cnblogs.com/Mainz/archive/2009/09/14/1566494.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值