小编典典

jQuery ajax http状态代码

ajax

我现在将脚本更改为jquery。这是我的旧javascript:

var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : (window.ActiveXObject ? new window.ActiveXObject("Microsoft.XMLHTTP") : false);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);

function updatePage() {
        if (request.readyState == 4) {
                if (request.status == 200) {
                    var response = request.responseText;
                    doSomething();
                } else if (request.status == 304) {
                    doSomethingElse();
                } else {
                }
        }
}

我现在想将其更改为jquery-ajax:

request = $.ajax({
    type: "GET",
    url: url,
    data: data,
    success: updatePage
});

像在旧脚本中一样,如何测试请求返回的状态码(和responseText)?


阅读 344

收藏
2020-07-26

共1个答案

小编典典

试试这个:

request = $.ajax({
    type: "GET",
    url: url,
    data: data,
    statusCode: {
      200: function() {
        doSomething();
       },
      304:function(){
        doSomethingElse();
       }
     }
});

要么:

request = $.ajax({
    type: "GET",
    url: url,
    data: data,
    complete: function(e, xhr, settings){
       if(e.status === 200){

       }else if(e.status === 304){

       }else{

       }
    }
});
2020-07-26