如何使用 jQuery 获取 HTTP 状态代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2955947/
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
How do I get the HTTP status code with jQuery?
提问by horgen
I want to check if a page returns the status code 401. Is this possible?
我想检查一个页面是否返回状态代码 401。这可能吗?
Here is my try, but it only returns 0.
这是我的尝试,但它只返回 0。
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
complete: function(xhr, statusText){
alert(xhr.status);
}
});
回答by Ravi Mittal
this is possible with jQuery $.ajax()
method
这可以通过 jQuery$.ajax()
方法实现
$.ajax(serverUrl, {
type: OutageViewModel.Id() == 0 ? "POST" : "PUT",
data: dataToSave,
statusCode: {
200: function (response) {
alert('1');
AfterSavedAll();
},
201: function (response) {
alert('1');
AfterSavedAll();
},
400: function (response) {
alert('1');
bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
},
404: function (response) {
alert('1');
bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
}
}, success: function () {
alert('1');
},
});
回答by b123400
The third argument is the XMLHttpRequest object, so you can do whatever you want.
第三个参数是 XMLHttpRequest 对象,因此您可以随心所欲。
$.ajax({
url : 'http://example.com',
type : 'post',
data : 'a=b'
}).done(function(data, statusText, xhr){
var status = xhr.status; //200
var head = xhr.getAllResponseHeaders(); //Detail header info
});
回答by baloo
Use the error callback.
使用错误回调。
For example:
例如:
jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
alert(xhr.status); }
});
Will alert 404
将警报 404
回答by GvS
I think you should also implement the error function of the $.ajaxmethod.
我觉得你也应该实现$.ajax方法的error函数。
error(XMLHttpRequest, textStatus, errorThrown)Function
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
错误(XMLHttpRequest,textStatus,errorThrown)函数
请求失败时调用的函数。该函数传递了三个参数:XMLHttpRequest 对象、一个描述发生的错误类型的字符串和一个可选的异常对象(如果发生)。第二个参数(除了 null)的可能值是“超时”、“错误”、“未修改”和“解析器错误”。
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
complete: function(xhr, statusText){
alert(xhr.status);
},
error: function(xhr, statusText, err){
alert("Error:" + xhr.status);
}
});
回答by Jigar Trivedi
I found this solution where you can simply, check the server response code using status code.
我找到了这个解决方案,您可以简单地使用status code检查服务器响应代码。
Example :
例子 :
$.ajax({
type : "POST",
url : "/package/callApi/createUser",
data : JSON.stringify(data),
contentType: "application/json; charset=UTF-8",
success: function (response) {
alert("Account created");
},
statusCode: {
403: function() {
// Only if your server returns a 403 status code can it come in this block. :-)
alert("Username already exist");
}
},
error: function (e) {
alert("Server error - " + e);
}
});
回答by vartec
$.ajax({
url: "http://my-ip/test/test.php",
data: {},
error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
回答by aircraft
I encapsulate the jQuery Ajax to a method:
我将 jQuery Ajax 封装到一个方法中:
var http_util = function (type, url, params, success_handler, error_handler, base_url) {
if(base_url) {
url = base_url + url;
}
var success = arguments[3]?arguments[3]:function(){};
var error = arguments[4]?arguments[4]:function(){};
$.ajax({
type: type,
url: url,
dataType: 'json',
data: params,
success: function (data, textStatus, xhr) {
if(textStatus === 'success'){
success(xhr.code, data); // there returns the status code
}
},
error: function (xhr, error_text, statusText) {
error(xhr.code, xhr); // there returns the status code
}
})
}
Usage:
用法:
http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
console(status_code, data)
}, function(status_code, err){
console(status_code, err)
})
回答by Phil
I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.
我在使用 ajax + jQuery v3 从 JSON API 获取响应状态代码和数据时遇到了重大问题。jQuery.ajax 仅在状态为成功时解码 JSON 数据,并且它还根据状态代码交换回调参数的顺序。呃。
The best way to combat this is to call the .always
chain method and do a bit of cleaning up. Here is my code.
解决这个问题的最好方法是调用.always
链方法并进行一些清理。这是我的代码。
$.ajax({
...
}).always(function(data, textStatus, xhr) {
var responseCode = null;
if (textStatus === "error") {
// data variable is actually xhr
responseCode = data.status;
if (data.responseText) {
try {
data = JSON.parse(data.responseText);
} catch (e) {
// Ignore
}
}
} else {
responseCode = xhr.status;
}
console.log("Response code", responseCode);
console.log("JSON Data", data);
});
回答by JoseMiguel
Test in WAMP SERVER apache2
在 WAMP SERVER apache2 中测试
abrir el httpd.conf y agregar esto:
abrir el httpd.conf y agregar esto:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
enable the next module on apache headers_module
restart all services
在 apache headers_module 上启用下一个模块
重启所有服务