我写了一个从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
}
答案 0 :(得分:3)
现在它发送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;
});