jquery ajax http状态码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12759627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:00:24  来源:igfitidea点击:

jquery ajax http status code

jqueryajax

提问by Zulakis

I am changing my scripts to jquery at the moment. This is my old javascript:

我现在正在将我的脚本更改为 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 {
                }
        }
}

I now want to change this to jquery-ajax:

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

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

How can I test for the status code (and the responseText) returned by the request, like I did in my old script?

我如何测试请求返回的状态代码(和 responseText),就像我在旧脚本中所做的那样?

回答by mgraph

try this:

尝试这个:

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

or:

或者:

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

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

       }else{

       }
    }
});

回答by techie_28

You need to just bind this request to an event like button click or something Like

你只需要将此请求绑定到一个事件,比如按钮点击或类似的东西

$('#btn').click({function(){
$.ajax({
    type: "GET",
    url: url,
    data: data,
    success: updatePage
});
});

You dont need to really keep this request against a variable as jQuery ajaxhas a success callbackwhich will help you to execute post success code

您不需要真正针对变量保留此请求,因为jQuery ajax有一个成功回调,这将帮助您执行成功后代码