簡體   English   中英

使用PHP的jQuery AJAX響應很難

[英]Difficulty with jQuery's AJAX response from PHP

我是AJAX的新手。 我試圖讓一個簡單的登錄腳本工作。 這是使用jQuery 1.6.4。 在下面的AJAX中,當用戶單擊按鈕時,它會將電子郵件地址和密碼發送到login.php。 這一切似乎都很好。 問題在於成功功能。 當電子郵件和密碼正確時,它應該返回true。 當它不起作用時它應該返回false。 使用Firebug,我發現它適用於console.log。 如果我寫警報(響應);它也可以正常工作。 但是,即使response等於true,條件總是計算為false。 我已嘗試過if(response=="true")if(response==="true") ,將變量放在函數外部,還有其他一些事情沒有成功。 有人會有任何想法如何解決這個問題?

謝謝你的任何幫助或想法,傑森。

AJAX:

$("#firstpage").live('pageinit', function (evt) {
$('#button').click(function(){       
var $form = $('#login'),
$inputs = $form.find("input"),
serializedData = $form.serialize();
$.ajax({
  type: 'POST',
  url: 'php/login.php',
  data: serializedData,
  success: function(response){
    console.log("Response: "+response);
    if(response=="true") 
    {
$('#firstpage #wrong').text("Login script is working");
} else {
$('#firstpage #wrong').text("Your email and password combination did not match.");
}

    },      
  dataType: 'json'
});
});  
});

如果有幫助,這是我的login.php腳本。

$email = $_POST['email'];
$password = $_POST['password'];
require_once("DB.php");
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); 
mysql_select_db($db) or die ("Unable to select database!"); 

$query = "SELECT * FROM member WHERE email='$email' AND password='".md5($_POST['password'])."'";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 

$num_rows = mysql_num_rows($result);
if($num_rows>0){
$output = true;
} else {
$output = false;
}
echo json_encode($output);

響應是一個對象,因為你有“dataType:'json'”。 jQuery將嘗試將responseText轉換為JSON。 如果您需要檢查服務器返回的數據,請嘗試使用

if (response === true) {

}

或者干脆

if (response) {

}

或者只是通過刪除數據類型讓jQuery返回字符串:'json'

不要使用帶有完全等號===引號。 采用

if (response === true)

因為PHP腳本返回true ,而不是"true"

我不喜歡PHP,但嘗試刪除關於true的引號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM