0
我写了一个函数,它从php文件中获取一些数据。当我解析它并使用警告框来显示它时,它工作正常,但是当我尝试返回未定义的值时。我不知道为什么会发生这种情况Javascript函数返回null
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
}
阿贾克斯是异步的 - 你返回名称变量,但Ajax请求尚未完成设置。 –