【问题标题】:Save a http request return value in a variable将 http 请求返回值保存在变量中
【发布时间】:2020-09-13 16:23:05
【问题描述】:

我尝试使用 http 请求和回调函数来获取数据,但是当我尝试打印时我得到未定义 变量。

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send(null);
}

var response;
httpGetAsync("https://localhost:44319/api/Food/Get",function(result){
    response = result;
})

console.log(response)

【问题讨论】:

    标签: javascript http callback return undefined


    【解决方案1】:

    尝试将console.log(response) 放入回调中。现在 console.log 在收到 http 响应之前被调用。

    【讨论】:

    • 我能以某种方式将返回的结果保存在响应变量中吗?
    • @LeventeMakszimus 现在变量 response 是结果,但它的范围只在函数 httpGetAsync("localhost:44319/api/Food/Get",function(result){ response = result; }) 所以所有的逻辑都应该去那里,如果你需要在收到 http 请求的响应后做一些事情
    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多