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

Ajax, JS function returning undefined value

本文关键字:未定义 返回 函数 JS Ajax      更新时间:2023-09-26

我对这一切都很陌生,我正在学习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;
?>

这就是我称之为检查电子邮件的地方

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;
	  }

更新

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

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;
	  }

您将立即返回状态,而实际的 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);
});