如何赚$.Get返回一个值

How to make $.get return a value

本文关键字:一个 何赚 Get 返回      更新时间:2023-09-26

我在JavaScript和jQuery中有这个代码,我需要修复它:

function valid_form() {
val_avail_email=valid_avail_email();
if (val_avail_email!="") {
$("#email_valid").html(val_avail_email);
return false;
}
return true;
}
function valid_avail_email() {
    var error="";
    $.get("valid_avail_email.php",{email:document.reg_form.email_reg.value},function(output) {
        error=output;
    });
    return error;
}

显然,我想让error变量包含valid_avail_email.php的输出,然后让valid_avail_email()函数返回该值。

以下是valid_avail_email.php中的代码:

<?php
include("config.php");
$email=$_GET["email"];
$sql="select email from users";
$sql_query=mysql_query($sql);
if (!$sql_query) {
    echo mysql_error();
}
$res_assoc = mysql_fetch_assoc($sql_query);
foreach ($res_assoc as $field=>$value) {
   if ($value==$email) {
       echo "please use another email this one is taken ";
   }
}
?>  

问题是$.get()函数发起异步ajax调用,这意味着,当ajax调用仍在运行时,函数返回。你必须在ajax回调函数中通知GUI,例如:

$.get("valid_avail_email.php",{email:document.reg_form.email_reg.value},function(output) {
  error=output;
  if (error !== '')
    alert('Sorry, use another email!');

});

您不需要执行foreach循环来检查电子邮件是否在db中。只需执行以下查询:

SELECT email FROM users WHERE email = '$email'

并检查结果是否包含任何项。此方法比使用"foreach"循环枚举所有电子邮件要快,因为数据库返回1或0个结果,如果您有一个大数据库,则不会返回数千个结果。

你的valid_avail_email()是ok..只要在JS中检查函数是否返回任何东西,如果是,则有警告显示错误:

var emailOk = valid_avail_email("blabla@email.com");
if(emailOk != ""){
//the following alert will show the error from php, it can show mysql_error() or "please use another email.." message
alert(emailOk);
//do stuff to abort the script
}