Javascript函数返回null

Javascript function returning null

本文关键字:null 返回 函数 Javascript      更新时间:2023-09-26

我写了一个函数,从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;
});