gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:15:29 25 4
gpt4 key购买 nike

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

这是我调用 checkEmail 的地方

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

关于javascript - Ajax,JS函数返回未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36007742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com