gpt4 book ai didi

JavaScript 函数返回 null

转载 作者:行者123 更新时间:2023-11-28 18:18:12 26 4
gpt4 key购买 nike

我编写了一个从 php 文件获取一些数据的函数。当我解析它并使用警报框显示它时,它工作正常,但是当我尝试返回该值时,它显示为未定义。我不知道为什么会发生这种情况

function getUser() {

var httpRequest = new createAjaxRequestObject();

httpRequest.open('GET', 'getUser.php', true);
var name;

httpRequest.onreadystatechange = function() {

if (httpRequest.readyState == 4) {

if (httpRequest.status == 200) {
name = JSON.parse(httpRequest.responseText);
alert(name); //this works just fine and display the name john
} else {
alert('Problem with request');
}
}
}

httpRequest.send();
return name; //however this is returning null
}

最佳答案

现在它发送 null ,因为一旦调用 httpRequest.send(); 就会获取该值。

在这种情况下,您需要将回调传递给将接收返回值的函数

这样改,

function foo(callback) {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method


}
}
};
httpRequest.open('GET', 'getUser.php', true);
httpRequest.send();
}

foo(function (result) {
var name = result;
});

关于JavaScript 函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446318/

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