jQuery

样例代码:

  

<html>
  <head>
    <title>hangge.com</title>
    <meta charset="utf-8"/>
    <script type="text/javascript" src="./jquery-1.11.1.min.js"></script>
    <script>
      //全局的ajax访问,处理ajax清求时session超时
      $.ajaxSetup({
         contentType:"application/x-www-form-urlencoded;charset=utf-8",
         complete:function(XMLHttpRequest,textStatus){
             //通过XMLHttpRequest取得响应头,sessionstatus,
             var sessionstatus=XMLHttpRequest.getResponseHeader("sessionstatus");
             if(sessionstatus=="timeout"){
                 //如果超时就处理 ,指定要跳转的页面(比如登陆页)
                 window.location.replace("/login/index.php");
             }
          }
       });
 
      //获取数据
      function getContent() {
        $.get("content.php", function (data){
                alert(data);
        });
      }
 
      //登录或注销
      function login(value) {
        $.get("login.php",{"login":value} , function (data){
                alert(data);
        });
      }
    </script>
  </head>
  <body>
    <button onclick="getContent()">获取数据</button>
    <button onclick="login(true)">登录</button>
    <button onclick="login(false)">注销</button>
  </body>
</html>

 

一、统一处理返回结果

我们可以将超时或是其他异常情况放置在返回结果中,前台统一解析结果来进行各种异常处理。

1,后台返回数据样例

比如后台返回如下格式的 JSON 数据,包括正常情况和异常情况。

//正常数据返回
{"state":1, "msg":"", "data":"欢迎访问hangge.com"}
 
//session超时数据返回
{"state":-1, "msg":"session超时,请重新登录!"}
 
//异常情况数据返回
{"state":0, "msg":"服务器繁忙,请稍后再试。"}

  

2,前台处理样例

 

//全局的ajax访问,处理ajax清求时异常
$.ajaxSetup({
   contentType:"application/x-www-form-urlencoded;charset=utf-8",
   complete:function(XMLHttpRequest,textStatus){
      //通过XMLHttpRequest取得响应结果
      var res = XMLHttpRequest.responseText;
      try{
        var jsonData = JSON.parse(res);
        if(jsonData.state == -1){
          //如果超时就处理 ,指定要跳转的页面(比如登陆页)
          alert(jsonData.msg);
          window.location.replace("/login/index.php");
        }else if(jsonData.state == 0){
          //其他的异常情况,给个提示。
          alert(jsonData.msg);
        }else{
          //正常情况就不统一处理了
        }
      }catch(e){
      }
    }
 });
 
//获取数据
function getContent() {
  $.get("content.php", function (data){
      var jsonData = JSON.parse(data);
      //只处理正常的情况
      if(jsonData.state == 1){
        alert(jsonData.data);
      }
   });
}

  

三、统一处理异常的HTTP状态码

我们还可以通过 Ajax 拦截,根据异常的 HTTP 状态码(404、500等)统一处理各种请求错误、服务器错误等情况。

$.ajaxSetup({

   contentType:"application/x-www-form-urlencoded;charset=utf-8",
   complete:function(XMLHttpRequest,textStatus){
   },
   statusCode: {
     404: function() {
         alert('数据获取/输入失败,没有此服务。404');
     },
     504: function() {
         alert('数据获取/输入失败,服务器没有响应。504');
     },
     500: function() {
         alert('服务器有误。500');
     }
   }
});

 

原文地址:https://www.cnblogs.com/flyingDragon/p/11956096.html