如何在Jquery POST中获得HTTP错误响应代码?
How do I get HTTP error response code in Jquery POST
我有一个用于向服务器发送请求的包装器函数,如果服务器返回401的代码,我需要做一些特定的事情,我不确定如何获得此数据
$.mobile.showPageLoadingMsg();
$.post(apiUrl+method,p,function(d) {
$.mobile.hidePageLoadingMsg();
console.log(d.success);
console.log(d.message);
if(d.success == true){
window[callback](d.data);
}
else{
if(d.message != null){
alert(d.message);
}
}
},'json')
.error(function() {
//need to check for 401 status here to do something
$.mobile.hidePageLoadingMsg();
alert("error");
});
如果我的服务器端代码抛出401异常,jquery .error函数拾取这只是因为它不是200 OK,但我需要检查它是否为401代码。
在error
回调中,检查xhr.status
,其中xhr
是函数的第一个参数
更新"promise"方法:从jQuery 1.5开始,我们可以调用。fail() promise来获取状态码,如下所示:
$.post( "example.php", function() {
alert( "success" );
}).fail(function(xhr) {
console.log(xhr.status);
});
注意,.error()承诺从jQuery 3.0开始被删除
相关文章:
- AJAX简单错误.XMLHttpRequest无法加载http://localhost/mpl/getPage.php.
- spring和angularJS(我得到了类似HTTP状态404的错误)
- $http服务未触发成功或错误回调
- 为什么我在Cloud9中的http请求总是返回错误
- 为什么我的$http.post返回一个400错误
- AngularJS$http.post调用返回502(坏网关)错误
- "所请求的名称已经作为不同类型的“”存在;HTTP 409响应错误
- 岗位http://localhost:3000/api/signup400(错误请求)
- $http GET URL更改并查找错误的资源
- 在AngularJS中使用$http.get检索JSON时出现错误400
- AngularJS $http GET 请求到本地 JSON 文件返回语法错误:意外令牌]
- 未捕获的错误: [$injector:modulerr] http ..(使用纯 HTML)
- AngularJS或JQuery解析错误格式的JSON(http get)
- 从 Ajax 获取由 ZombieJS 的异步点击事件触发的 Http 错误
- AngularJs 错误:$http请求虽然在控制器中定义
- GWT应用程序中出现错误HTTP 404(“Script Tag Failure-no status available
- 在openmeetings中上载/共享文件时出现错误HTTP:500
- Angular HTTP GET 与 TypeScript 错误 http.get(..).映射不是 [null] 中的
- browserify 错误:http.createServer 不是一个函数
- 未捕获错误:[$http:badreq] Http 请求配置 url 必须是字符串 (AngularJS)