我对 AJAX 还比较新手。我正在尝试让一个简单的登录脚本工作。这是使用 jQuery 1.6.4。在以下的 AJAX 中,当用户点击按钮时,它会将电子邮件地址和密码发送到 login.php。
那似乎都很好用。问题出在成功函数上。当电子邮件和密码正确时,它应该返回 true。当它不工作时,它应该返回 false。使用 Firebug,我看到 console.log 可以工作,如果我写 alert(response); 也可以正常工作。但是,即使 response 等于 true,条件语句始终为 false。我已经尝试了 if(response=="true")
和 if(response==="true")
,将变量放在函数外面等等一些其他的东西,但都没有成功。是否有人有任何想法如何解决这个问题?
感谢任何帮助或想法, Jason。
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);
"true"
而不是一个布尔值true
。在 PHP 中更改为$output = "success"
,在 Javascript 中更改为response === "success"
或者更具有意图性的内容,这样你就可以缩小问题范围。 - potenchtypeof response == 'boolean'
的语句。 - jwerremd5
更好的密码哈希算法。 - jeroen