Jay*_*lya 3 php mysql ajax jquery firebug
我使用以下方法来调用php:
function validateEmaiAjax(email){
val = null;
$("#warning").load("https://localhost/Continental%20Tourism/register_ajax.php",{email: email}, function(rspns, stat, xml){
val = rspns;
});
if(val == ".")
return true;
else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我的PHP代码是:
<?php
$dbc = mysqli_connect("localhost","root","pass","continental_tourism") OR die(mysqli_connect_error());
$email = $_REQUEST['email'];
$query = "SELECT email FROM customer_info WHERE email = '$email' ";
$r = mysqli_query($dbc, $query) OR die(mysqli_error($dbc));
if(mysqli_num_rows($r) > 0)
echo "Email address exists!";
else
echo ".";
?>
Run Code Online (Sandbox Code Playgroud)
基本上这会检查数据库,如果存在电子邮件显示"存在电子邮件地址!" 如果不是我想return true(所以我回应"."并比较它).奇怪的是,如果我在if(val == ".")程序附近使用firebug设置断点并且返回true.如果我删除该断点函数总是返回false.我不明白为什么会这样.请帮忙!谢谢.
您遇到此问题的原因是您已执行异步请求.这意味着if(rspns == ".")将在从服务器收到响应之前到达,结果将始终为false.
为了在函数中包装此代码,返回一个布尔值,并且不需要回调函数(阻塞过程),您将需要使用同步请求:
function validateEmaiAjax(email) {
// This is the correct way to initialise a variable with no value in a function
var val;
// Make a synchronous HTTP request
$.ajax({
url: "https://localhost/Continental%20Tourism/register_ajax.php",
async: false,
data: {
email: email
},
success: function(response) {
// Update the DOM and send response data back to parent function
$("#warning").html(response);
val = response;
}
});
// Now this will work
if(val == ".") {
return true;
} else {
$("#warning").show();
return false;
}
}
Run Code Online (Sandbox Code Playgroud)