简体   繁体   English

将 http 请求返回值保存在变量中

[英]Save a http request return value in a variable

I try to get data by using http request and callback function but i get undefined when i try to print the variable.我尝试通过使用 http 请求和回调 function 来获取数据,但是当我尝试打印变量时我得到未定义。

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)

Try put console.log(response) inside callback.尝试将console.log(response)放在回调中。 Right now console.log is called before http response was received.现在 console.log 在收到 http 响应之前被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM