[英]jQuery AJAX and PHP return true/false
我想知道如何使用jQuery AJAX從PHP腳本檢索return true或false。 這是我當前的ajax調用代碼,即使登錄實際上沒有成功,它也總是可以直接轉到輸入用戶名的個人資料頁面。
$("#signInForm").submit(function() {
$(document).ajaxStart(function() {
$("#loading" ).show();
});
$.ajax({
url: "/ajax/signIn.php", // Action of the form
data: $("#signInForm").serialize(), // Send forms data to server
dataType: "JSON", // Take response as JSON
type : "POST", // Send form by post or get
complete: function(result) {
$(document).ajaxStop(function() {
$("#loading" ).hide();
});
$("#ajaxResponse").html(result.responseText);
$("#ajaxResponse").slideDown("slow");
var username = $("#usernameSignIn").val();
setTimeout(function() {
window.location.href = "/profile.php?username=" + username;
}, 3000);
}
});
return false; // Default submit return false
});
呼叫complete
觸發complete
觸發---不考慮結果-我想只要response
-完全可以接受。
否則,您可能想使用success
,但是在這種情況下,您需要做的就是根據該response
確定要做什么
即:
if(response === true){ //proceed }else{ alert("error!"); }
您必須自己輸入邏輯-因為complete
與success
僅與數據的實際傳輸有關,而與數據的內容無關。
因此,在您的代碼中:
$("#signInForm").submit(function() {
$(document).ajaxStart(function() {
$("#loading" ).show();
});
$.ajax({
url: "/ajax/signIn.php", // Action of the form
data: $("#signInForm").serialize(), // Send forms data to server
dataType: "JSON", // Take response as JSON
type : "POST", // Send form by post or get
complete: function(result) {
$(document).ajaxStop(function() {
$("#loading" ).hide();
});
$("#ajaxResponse").html(result.responseText);
$("#ajaxResponse").slideDown("slow");
if(result.success === true){
var username = $("#usernameSignIn").val();
setTimeout(function() {
window.location.href = "/profile.php?username=" + username;
}, 3000);}
else { //the result.responseText is probably suitable here, eh? so you could just:
$("#ajaxResponse").slideUp(5000); }
}
});
return false; // Default submit return false
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.