【问题标题】:Is there a way to trigger the done function on a jQuery AJAX call?有没有办法在 jQuery AJAX 调用上触发 done 函数?
【发布时间】:2020-05-01 06:48:58
【问题描述】:

我有一个功能应该只在 AJAX 调用完成后才能继续,但如果我的本地存储中已经有上次会话的数据,我希望能够跳过该 AJAX 调用。

我当前的代码:

$.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}}
}

提前致谢!

【问题讨论】:

  • 将该逻辑抽象为一个单独的方法,您将在 .done() 回调中调用该方法。
  • 这仍然会执行 ajax 调用,如果该数据在本地存储中,我想跳过整个调用。所以我可以使用本地存储数据,而不必使用 ajax 再次获取数据。

标签: javascript jquery ajax local-storage


【解决方案1】:

反过来做。

在本地检查数据,如果您已经拥有,甚至不要发送请求。

将数据包装在 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
});

另一种方法是忘记 localStorage,只设置适合 caching headers 的 Web 服务。然后就可以发起 HTTP 请求了,但是如果缓存信息显示浏览器缓存包含最新数据,则根本不会发起 HTTP 请求。

您无需重新发明数据的本地缓存。 HTTP 已经融入其中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    相关资源
    最近更新 更多