【问题标题】:Force ajax call to clear cache强制ajax调用清除缓存
【发布时间】:2011-05-02 21:31:12
【问题描述】:

我有一个 cms,我可以在其中更改对象的位置。每次位置更改后,ajax 调用都会更新整个对象列表。但不幸的是,一些数据存储在缓存中,没有可见的变化。有没有办法用 javascript/request/other 强制清除缓存?我在$.ajax 中尝试过'cache: false' 但它不起作用。

这是一个示例页面:

http://ntt.vipserv.org/manage/playforward

还有我的 js:

$(".object-position").livequery("change", function() {
    $("#objects-list input").attr('disabled', true);
    var action = $(this).attr('name');
    var position = $(this).attr('value');
    var id = $(this).attr("id");
    var model = id.split("-")[0];
    var object_id = id.split("-")[1];

    $("#loader").show();
    $("#loader").fadeIn(200);

    $.ajax({
        type: "POST",
        async: true,
        url: "/manage/update_position/",
        data: "action=" + action + "&model=" + model + "&object_id=" + object_id + "&position=" + position,
        dataType: "json",
        success: function(data){
            $("#loader").fadeOut("fast", function () {
                $("#loader").hide();
            });
            $("objects-list").html(data["html"]);
            $("#message").show();
            $("#message").fadeIn(400).html('<span>'+data["message"]+'</span>');
            setTimeout(function(){
                $("#message").fadeOut("slow", function () {
                    $("#message").hide();
                });
            }, 1500); 
        }
    });
    $("#objects-list input").attr("disabled", false);
    return false;
});

【问题讨论】:

    标签: jquery ajax caching xmlhttprequest clear-cache


    【解决方案1】:

    cache: false 所做的是将时间添加到请求数据中,因此每个请求实际上都是唯一的,因此绕过了浏览器的缓存。我想知道您使用的是数据字符串而不是对象这一事实是否会在此处引起问题。尝试使用对象:

    $.ajax({
        type: "POST",
        async: true,
        url: "/manage/update_position/",
        data: {
            "action": action.
            "model": model,
            "object_id": object_id,
            "position": position
        },
        cache: false,
        dataType: "json",
        success: function(data){
            //[snip]
        }
    });
    

    【讨论】:

    • 我确实确认 - 这确实有效。 cache:false 为 url 添加时间戳,因此,每次加载新内容时。
    【解决方案2】:

    只需替换

    url: "/manage/update_position/",
    

    url: "/manage/update_position/?nocache="+Math.random(),
    

    强制重新加载页面而不使用浏览器的缓存。

    【讨论】:

    • 这很容易搞砸路由系统。如果您要手动执行此操作,请将其设为请求参数:"/manage/update_position/?nocache="+Math.random()
    • 是的,你完全正确。我忘记在我的原始帖子中包含"?"。应该是:"/manage/update_position/?"+Math.random(),
    【解决方案3】:

    你有

    $("objects-list").html(data["html"]);
    

    试试这个:

    $(".objects-list").html(data["html"]); // forgot leading dot?
    

    此外,您似乎正在尝试将.objects-list 表的内容替换为包含&lt;table&gt; 元素本身的一些html。因此,在 .html() 内容替换之后,您将拥有 &lt;table...&gt;&lt;table...&gt; 等。

    【讨论】:

      猜你喜欢
      • 2017-05-19
      • 1970-01-01
      • 2019-01-28
      • 2016-02-18
      • 2014-12-23
      相关资源
      最近更新 更多