缓存来自ajax调用的结果,以防止多次运行它们

时间:2014-01-31 22:44:22

标签: javascript php jquery ajax caching

在我的项目中,我有一个启动js函数的php文件进行ajax调用。 我的问题是,如果用户在浏览器功能上刷新php页面重新进行ajax调用等等。 我需要缓存ajax执行的第一个结果,这样如果刷新完成后使用缓存中的数据而不是再次进行ajax调用。

我的电话是

if (xmlHttp)
    {
    // try to connect to the server
    try
    {
      xmlHttp.open("GET", "top10.php?P1="+oStxt, true);
      xmlHttp.onreadystatechange = handleRequestStateChange10;
      xmlHttp.send(null);
    }
        // display the error in case of failure
        catch (e)
    {
        alert("Can't connect to server:\n" + e.toString());
    }

如何防止浏览器页面刷新多次ajax调用?

提前致谢

1 个答案:

答案 0 :(得分:1)

我建议以下流程:

  • 在请求之前哈希您的请求URL(MD5?)
  • 检查您的 localStorage (或类似)是否具有此哈希的值
  • 如果没有价值
    • 做你的要求
    • 使用hash作为键
    • 将返回的数据保存在localStorage中
    • 渲染页面
  • 如果有价值
    • 从localStorage加载
    • 渲染页面

容易!