简体   繁体   English

使用AJAX返回JSON对象

[英]Using AJAX to return a JSON Object

I'm trying to use AJAX (through jQuery) to return a bit of JSON from an API, and then store that JSON in localStorage as a string. 我正在尝试使用AJAX(通过jQuery)从API返回一点JSON,然后将该JSON作为字符串存储在localStorage中。 Whenever the function runs, I want it to check localStorage for the key, and return that value if it exists. 每当函数运行时,我都希望它检查密钥的localStorage并返回该值(如果存在)。 If it does not exist, then it should contact the API for the object, save it to localStorage, and then return it. 如果不存在,则应联系该对象的API,将其保存到localStorage,然后返回它。

The problem that I'm having is this: the function NEVER returns the JSON object the first time (when it's not stored in localStorage). 我遇到的问题是:函数从不(在未存储在localStorage中时)第一次返回JSON对象。 It has no problem saving it to localStorage, and it always pulls it from localStorage just fine, but even right after using the returned object in the previous line, the function won't return it. 将它保存到localStorage并没有问题,并且总是可以将其从localStorage中拉出来,但是即使在上一行中使用返回的对象之后,该函数也不会返回它。 The console just says "undefined". 控制台仅显示“未定义”。

The code I'm using is below (edited slightly since the API is private): 我正在使用的代码如下(由于API是私有的,因此进行了一些编辑):

window.get_company = function() {
    var full = window.location.host;
    var parts = full.split('.');
    var subdomain = parts[0];

    if ( localStorage.getItem("company_" + subdomain) === null ) {
        $.getJSON("https://api.testingapp.com/subdomains?name=" + subdomain).then( function(data) {
            localStorage.setItem("company_" + subdomain, JSON.stringify(data));
            return JSON.stringify(data);
        });
    } else {
        return localStorage.getItem("company_" + subdomain);
    }
}

Thanks so much for your help! 非常感谢你的帮助!

Your call to $.getJSON is asynchronous. 您对$.getJSON调用是异步的。 The return JSON.stringify(data) doesn't happen until later, after your original get_company function has returned. return JSON.stringify(data)直到稍后,在原始的get_company函数返回后才发生。 One way to deal with this would be to use promises or callbacks. 解决此问题的一种方法是使用promise或回调。

For example, using jQuery's Deferred object (promises): 例如,使用jQuery的Deferred对象(承诺):

window.get_company = function() {
    var deferred = $.Deferred();
    var full = window.location.host;
    var parts = full.split('.');
    var subdomain = parts[0];

    if ( localStorage.getItem("company_" + subdomain) === null ) {
        $.getJSON("https://api.testingapp.com/subdomains?name=" + subdomain).then(function(data) {
            localStorage.setItem("company_" + subdomain, JSON.stringify(data));
            return deferred.resolve(JSON.stringify(data));
        });
    } else {
        deferred.resolve(localStorage.getItem("company_" + subdomain));
    }

    return deferred;
}

// to use:
window.get_company().then(function(result) {
  // do something with the result
})

In the following link you have some solutions/workarounds: 在以下链接中,您有一些解决方案/解决方法:

(Check the SECOND answer, not the accepted one) (检查第二个答案,而不是接受的答案)

Return value for function containing jQuery $.post() function 包含jQuery $ .post()函数的函数的返回值

So, although it's technically possible to make the call synchronous and return the value, it's not recommended. 因此,尽管从技术上讲可以使调用同步并返回值,但不建议这样做。 Your method should become async and instead of returning a value, it would call a callback when finished, so you'd have: 您的方法应变为异步方法,而不是返回值,而是在完成后将调用回调,因此您将:

window.get_company = function(onSuccess) {
    var full = window.location.host;
    var parts = full.split('.');
    var subdomain = parts[0];

    if ( localStorage.getItem("company_" + subdomain) === null ) {
        $.getJSON("https://api.testingapp.com/subdomains?name=" + subdomain).then( function(data) {
            localStorage.setItem("company_" + subdomain, JSON.stringify(data));
            onSuccess(JSON.stringify(data));
        });
    } else {
        onSuccess(localStorage.getItem("company_" + subdomain));
    }
}

Then, instead of calling like this: 然后,不要像这样调用:

company = window.get_company(); //This fails

You would call 你会打电话

//This works
window.get_company(function(returnValue){
   company = returnValue;
});

That is one way, there are others, like returning a promise 那是一种方式,还有其他方式,例如兑现承诺

Cheers, from La Paz, Bolivia 来自玻利维亚拉巴斯的欢呼声

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

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