简体   繁体   English

等待来自异步 ajax tfrom api 调用的完整响应

[英]wait for complete response from async ajax tfrom api call

I have this ajax call in vanilla javascript which calls an api asynchronously and need to cache the response in localstorage.我在vanilla javascript中有这个ajax调用,它异步调用api并且需要在localstorage中缓存响应。 Here is my code:这是我的代码:

var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                console.log(xhttp.responseText);
                localStorage.setItem('Data', JSON.parse(xhttp.responseText));
            }
        };
        xhttp.open("GET", "/api/orgData", true);
        xhttp.send();

Problem is what I see for the value of Data in the local storage is [object object] although console.log prints the value of xhttp.responseText.问题是我在本地存储中看到的 Data 值是 [object object] 尽管 console.log 打印了 xhttp.responseText 的值。 I guess the issue has do with api response is not complete yet (not sure why this.readyState == 4 && this.status == 200 is not helping).我猜这个问题与 api 响应尚未完成有关(不确定为什么 this.readyState == 4 && this.status == 200 没有帮助)。 Could you please help to solve this issue so that it caches the data into local storage when the result is fully back from api.您能否帮助解决此问题,以便在结果完全从 api 返回时将数据缓存到本地存储中。 Also I am making this call in head of my html and I can only use vanilla javascript no jquery or other things.另外,我在我的 html 的头部进行了这个调用,我只能使用 vanilla javascript 没有 jquery 或其他东西。 Thanks in advance提前致谢

The problem you have here is that localStorage only stores strings, it doesn't store objects.你在这里遇到的问题是localStorage只存储字符串,它不存储对象。 So in this precise case what you have is the result of applying toString on your object.因此,在这种精确的情况下,您拥有的是在对象上应用toString的结果。

A solution would be to store the JSON:一个解决方案是存储 JSON:

localStorage.setItem('Data', xhttp.responseText);

And when you need the value you do当你需要你的价值时

var thing = JSON.parse(localStorage.getItem('Data'));

Be careful though that localStorage is limited in size, you'd better store just the important values.尽管 localStorage 的大小有限,但请注意,您最好只存储重要的值。

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

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