简体   繁体   English

AJAX请求:如何为未处理的HTTP状态代码实现“其他”条件?

[英]AJAX requests: How can I implement an “else” condition for unhandled HTTP status codes?

I am trying to react to the HTTP status codes in some AJAX. 我正在尝试对某些AJAX中的HTTP状态代码作出反应。 I am successful in reacting to specified status codes, but I do not want to have to check for every single one. 我可以对指定的状态代码做出成功的反应,但是我不想每次都检查一次。 Is there a way to write an else statement in the following code? 有没有办法在以下代码中编写else语句? Or does AJAX not do that? 还是AJAX不这样做?

$(function () {
    var url = "google.com";
    $.ajax(url,
            {
                statusCode: {
                    200: function () {
                        //react to status code 200
                    },
                    404: function () {
                        //react to status code 404
                    },
                    503: function () {
                        //react to status code 503
                    }
                    //if neither 200, 404, or 503, then react some way
                }
            });
});

I have tried writing else , using , , using nothing, etc. No success. 我尝试编写else ,using ,什么也不使用,等等。没有成功。 And I don't think the generic switch statement will work with what I am trying to do. 而且我认为通用的switch语句不能满足我的尝试。

Here's an example of how you can check the HTTP response code: 这是如何检查HTTP响应代码的示例:

var xhr = new XMLHttpRequest();
xhr.onload = function()
{
  switch (this.status)
  {
    case 200: console.log("The file exists!"); break;
    case 404: console.log("The file does not exist."); break;
    default:  console.log("Something else happened..."); break;
  }
};
xhr.open("get", "http://localhost:3000/something.png", true);
xhr.responseType = "blob";
xhr.send();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM