简体   繁体   English

有没有办法在 jQuery AJAX 调用上触发 done 函数?

[英]Is there a way to trigger the done function on a jQuery AJAX call?

I have a function that should only continue after an AJAX call has been completed, but I want to be able to skip that AJAX call if I already have the data from last session in my localstorage.我有一个函数应该只在 AJAX 调用完成后继续,但是如果我的本地存储中已经有了上一个会话的数据,我希望能够跳过该 AJAX 调用。

My current code:我目前的代码:

$.when(getAddresses()).done(function (data) {
        addresses = data.data;;

        localStorage['addresses'] = JSON.stringify(addresses);

        {{Rest of the code that should be executed after the AJAX call}}
}

Thanks in advance!提前致谢!

Do it the other way around.反过来做。

Check for the data locally and don't even send the request if you already have it.在本地检查数据,如果您已经拥有,甚至不要发送请求。

Wrap the data in a promise so it will always have the same API no matter where you fetch it from.将数据包装在一个 promise 中,因此无论您从何处获取数据,它都将始终具有相同的 API。

async function get_data() {
    let addresses = localStorage.getItem('addresses');
    if (addresses) {
         return JSON.parse(addresses);
    }
    let ajaxData = await getAddresses();
    addresses = ajaxData.data;
    localStorage.setItem('addresses', JSON.stringify(addresses));
    return addresses;
}

get_data().then(data => {
    // Rest of the code that should be executed after the AJAX call
});

Another approach would be to forget about localStorage and just have the web service set suitable caching headers .另一种方法是忘记 localStorage 并让 Web 服务设置合适的缓存标头 Then you can make the HTTP request, but if the cache information shows that the browser cache contains up to date data it won't make the HTTP request at all.然后您可以发出 HTTP 请求,但如果缓存信息显示浏览器缓存包含最新数据,则它根本不会发出 HTTP 请求。

You don't need to reinvent local caching of data.您不需要重新发明数据的本地缓存。 HTTP has it baked in. HTTP 已经融入其中。

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

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