AJAX 请求:如何为未处理的 HTTP 状态代码实施 "else" 条件?
AJAX requests: How can I implement an "else" condition for unhandled HTTP status codes?
我正在尝试对某些 AJAX 中的 HTTP 状态代码做出反应。我成功地对指定的状态代码做出了反应,但我不想检查每一个状态代码。有没有办法在下面的代码中写一个 else
语句?还是 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
}
});
});
我试过写 else
、使用 ,
、什么都不用等等。没有成功。而且我认为通用的 switch
语句不会与我正在尝试做的事情一起工作。
以下是如何检查 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();
我正在尝试对某些 AJAX 中的 HTTP 状态代码做出反应。我成功地对指定的状态代码做出了反应,但我不想检查每一个状态代码。有没有办法在下面的代码中写一个 else
语句?还是 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
}
});
});
我试过写 else
、使用 ,
、什么都不用等等。没有成功。而且我认为通用的 switch
语句不会与我正在尝试做的事情一起工作。
以下是如何检查 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();