Ajax,JS函数返回未定义的值

时间:2016-03-15 09:49:33

标签: javascript php ajax

我对这一切都很新,我想要学习Ajax以及Javascript,我从php文件中获取值,但是当我尝试返回方法中的值时,我得到一个未定义的值我登录控制台。我在尝试了很多事情但没有成功。有人可以就此教育我。请批评我的代码我确定有很多不好的做法。

谢谢



 function checkEmail(){
    var xhttp; 
    var status;

    xhttp = new XMLHttpRequest();

    var email = document.getElementById('email2').value;
    
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
            var xmlResponse = xhttp.responseText;      
            status = xmlResponse;
            
        }
    };


    xhttp.open("GET", "php/ajaxCom.php?email="+email, true);
    xhttp.send();

    return status;
 }






<?php
	include 'base.php';
	$status;

	$email_in_use = $_GET['email'];

	$query = mysqli_query($link, "SELECT * FROM users WHERE email='".$email_in_use."'");

	if(mysqli_num_rows($query) > 0){
	    $status = "false";
	}else{
		$status = "true";
	}
	echo $status;
?>
&#13;
&#13;
&#13;

这就是我所说的checkEmail

&#13;
&#13;
function getStatus(field, name, value) {
	    var status = null;

	    if (!field.attr('required')) return null;
	    if (!value) status = 'Please fill out the required field: ' + name;
	    else if (emailField.test(name) || emailField.test(field.attr('type'))) {

	       var b = checkEmail();
	       console.log(b);
	      if (!emailValue.test(value)) {
	      	status = 'Please enter a valid email address for: ' + name;
	      	}else if ( b == "false"){
	      		alert("im here");
	    	 status = 'Please enter a valid email this email already has an acount';
	    	}


	    }
	    return status;
	  }
&#13;
&#13;
&#13;

更新

统计信息警报正确显示,但控制台日志仍显示未定义

&#13;
&#13;
function getStatus(field, name, value) {
	    var status = null;

	    if (!field.attr('required')) return null;
	    if (!value) status = 'Please fill out the required field: ' + name;
	    else if (emailField.test(name) || emailField.test(field.attr('type'))) {
	    	var b;
	    	
	       checkEmail(function(status) {
    			alert('Status: ' + status);
    			b = status;
			});
	       console.log(b);


	      if (!emailValue.test(value)) {
	      	status = 'Please enter a valid email address for: ' + name;
	      	}else if ( b == "false" || b == "true"){
	      		alert("im here");
	    	 status = 'Please enter a valid email this email already has an acount';
	    	}


	    }
	    return status;
	  }
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您立即返回状态,其中实际的AJAX调用返回异步

您需要更改流量,以便 checkEmail 接受回调函数作为参数而不是返回它。这样的事情:

function checkEmail(callback) {
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
        var xmlResponse = xhttp.responseText;      
        status = xmlResponse;

        callback(status);
    }
};

...

checkEmail(function(status) {
    alert('Status: ' + status);
});
相关问题