如何从AJAX响应中查找值(true或false)

How to find value (true or false) from AJAX response?

本文关键字:true false 查找 AJAX 响应      更新时间:2023-09-26

我已经编写了一个脚本注册用户。在最后一步中,我需要函数中的值true或false来发现电子邮件是否已经存在。

function do_register(user_email){
    if (!isemailexist(user_email))  {
    document.getElementById("error").innerHTML="email is already exist, please change!!";
    document.regForm.user_email.focus()
    return false;
    } 
if (user_email=="") {
    document.getElementById("error").innerHTML="email is emphy!!";
    document.regForm.user_email.focus()
    return false;
    } 
if(document.regForm.user_name.value!=""){ process_register();} } 
function isemailexist ()
    xmlHttp.onreadystatechange=function () {
    if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
    var str=xmlHttp.responseText;
    var res=JSON.parse(str);
    if (res[0]=="no"){  
    return false;
    }
    }
    haha=xmlHttp.onreadystatechange.test(res[0]); ///I used test(); methode  in order to find value true or false
    }

我试了很多,但没有一个能告诉我是真是假!

我已经更新了上面的脚本,我希望它更好。更多代码:

PHP代码

if(mysql_num_rows($result)>0){ //  email is already exist
     $phpArray = array("no","Erroremail is aleady exist");
     echo json_encode($phpArray);
 }

你做的事情有点太复杂了。当响应为false时,不需要制作数组,因为您已经在告诉用户电子邮件已经存在。

而不是做

if(mysql_num_rows($result)>0){ //  email is already exist
     $phpArray = array("no","Erroremail is aleady exist");
     echo json_encode($phpArray);
}

只需在服务器端执行此操作。

if(mysql_num_rows($result)>0){ //  email is already exist
     return false;
}

当您不再使用数组时,响应会发生变化,您需要稍微调整一下代码。从res[0]中删除[0]


然后你的服务器响应将是错误的,所以更改

if (res[0]=="no"){  
    return false;
}

if (res==false){  
    return false;
}
else{
//continue...
}