我写了一个从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;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句