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請求尚未完成設置。 –