我遇到以下代码的奇怪行为:
// Log in the user if credentials are correct
function login() {
$.post("http://localhost/auth/login", {
username : $("#modal-login-username").val(),
password : $("#modal-login-password").val(),
autoLogin : autoLogin,
_token : $("#modal-login-token").val()
},
function(result) {
console.log("1"); // This is not printed
if(result === "OK") {
window.location.href = "http://localhost/home";
} else {
console.log("2"); // This is not printed
$("#modal-login-message-error").removeClass("hidden");
}
});
console.log("3"); // This is printed
};
在此函数中,我检查登录用户的PHP脚本是否返回“OK”。如果身份验证成功,则用户被正确地重定向到http://localhost/home
但如果出现问题,则返回ERROR
状态为500
的字符串,但不执行else语句。
答案 0 :(得分:3)
该回调函数仅在suucess上调用。您可以将您的电话放在帖子的.always()方法中:
var jqxhr = $.post( "example.php")
.always(function() {
console.log("1"); // This is not printed
if(result === "OK") {
window.location.href = "http://localhost/home";
} else {
console.log("2"); // This is not printed
$("#modal-login-message-error").removeClass("hidden");
}
});
有关详细信息,请查看jQuery页面http://api.jquery.com/jQuery.post/
甚至更好:
var jqxhr = $.post( "example.php", function() {
window.location.href = "http://localhost/home";
}).fail(function() {
console.log("2"); // This is not printed
$("#modal-login-message-error").removeClass("hidden");
});
答案 1 :(得分:0)
$.post(...).fail(function () {
//handle failure here
});