Ajax向函数返回值的问题 [英] Problem with ajax return value to a function
问题描述
我正在尝试将ajax请求中的值返回给表单提交上的函数.
i am trying to return value from ajax request to a function on form submit.
代码如下:
function validateEmail(){
if(email.val() == "")
{
$("#emailerror").html("Enter Email...");
return false;
}
else {
$.ajax({
type: "POST",
data: "email="+email.val(),
url:'emailcheck.php',
beforeSend: function(){
$("#emailerror").html("Checking Email...");
},
success: function(data){
if(data == "invalid")
{
$("#emailerror").html("Invalid Email");
return false;
}
else if(data != "0")
{
$("#emailerror").html("Email Already Exist");
return false;
}
else
{
$("#emailerror").html("OK");
return true;
}
}
});
}
}
在表单提交时,我正在调用该函数并检查ajax响应的返回值:
On form submit, i am calling the function and checking the return value from ajax response:
$('#myForm').submit(function(){
if(validateEmail())
{
alert('returning true');
return true;
}
else
{
return false;
}
});
但是,当返回值为'true'时,不会执行该代码.函数validateEmail()返回false.
But, the code is not executed when the return value is 'true'. The function validateEmail() return false.
请帮我弄清楚哪里出了问题.
Pls help me to figure out where i went wrong..
谢谢.
推荐答案
AJAX中的"A"代表异步".
The "A" in AJAX stands for "asynchronous".
在validateEmail
的else
分支中,您正在启动对emailcheck.php
的异步请求. validateEmail
将在您的PHP文件响应之前返回;然后您的emailcheck.php
脚本会响应,jQuery将调用您的success
回调,但是没有人会注意它返回的内容.就表单验证而言,结果是您的validateEmail
看起来像这样:
In the else
branch of validateEmail
, you're launching an asynchronous request to emailcheck.php
. validateEmail
will return before your PHP file responds; then your emailcheck.php
script does respond, jQuery will call your success
callback but no one will pay attention to what it returns. The result as far as form validation is concerned, is that your validateEmail
looks like this:
function validateEmail() {
if(email.val() == "") {
$("#emailerror").html("Enter Email...");
return false;
}
else {
// Your $.ajax() might as well not even be here as
// validateEmail will return before $.ajax() gets a
// response from emailcheck.php
return;
}
}
您可以尝试 $.ajax
的async:false
选项,或者重新编写所有逻辑能够等待异步请求返回.
You could try the async:false
option for $.ajax
or rework all your logic to be able to wait for the asynchronous request to return.
此外,validateEmail
的第二个分支不返回false
,它根本不返回任何东西,但这仍然不是真实值.
Furthermore, the second branch of validateEmail
does not return false
, it doesn't return anything at all but that's still not a true value.
这篇关于Ajax向函数返回值的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!