jQuery ajax 处理 401 未经授权
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10267683/
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
jQuery ajax handle 401 Unauthorized
提问by Prasad Rajapaksha
I am calling third party web page using jQuery ajax. According to their page they sent me status code 200 if log-in success and 401 if log-in unsuccessful. Here is my jquery code sample. This code works fine on IE but not work on Chrome or Firefox. What could be the issue?
我正在使用 jQuery ajax 调用第三方网页。根据他们的页面,如果登录成功,他们会向我发送状态代码 200,如果登录不成功,他们会向我发送状态代码 401。这是我的 jquery 代码示例。此代码在 IE 上运行良好,但不适用于 Chrome 或 Firefox。可能是什么问题?
$.ajax({
type: 'GET',
url: hostURL + 'j_teo_security_check?callback=?',
dataType: 'json',
data: ({j_username : $("#inp_user_name").val(), j_password: $("#inp_user_pwd").val()}),
statusCode: {
401:function() { alert("401"); },
404:function() { alert("404"); },
200:function() { alert("200"); },
201:function() { alert("201"); },
202:function() { alert("202"); }
},
complete: function(httpObj, textStatus){
alert(httpObj.status);
},
error: function(){
alert("error");
},
async: false
});
I tried all the functions error, success, complete, and statusCode. None of them handle the 401 error.
我尝试了所有功能错误、成功、完成和状态代码。他们都没有处理 401 错误。
采纳答案by Prasad Rajapaksha
I could fix it as bellow.
我可以修复它如下。
$(document).ready(function(){
$("#cmdLogin").click(function(){
var request = $.ajax({
url : hostURL + 'j_teo_security_check',
data: ({j_username : $("#inp_user_name").val(), j_password: $("#inp_user_pwd").val()}),
dataType : "jsonp",
timeout : 5000
});
request.success(function() {
loginSuccess();
});
request.error(function(httpObj, textStatus) {
if(httpObj.status==200)
loginSuccess();
else
loginFail();
});
});
})
What I did was added timeout since 401 error never came back. Since it goes to error function even with status code 200 and parsing errors I made it to ignore status 200 inside the error.
我所做的是添加超时,因为 401 错误再也没有回来。由于即使状态代码为 200 和解析错误,它也会进入错误功能,因此我忽略了错误中的状态 200。
回答by bmurmistro
Ok, it appears that you're using jsonp and I think it might be a limitation of jsonp. Take a look.
好的,看来您正在使用 jsonp,我认为这可能是 jsonp 的限制。看一看。
Looks like there is a solution on the last post. Hope this helps!
看起来上一篇文章有解决方案。希望这可以帮助!