停止缓存 jQuery .load 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/168963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:44:26  来源:igfitidea点击:

Stop jQuery .load response from being cached

jqueryajaxcaching

提问by dragonmantank

I have the following code making a GET request on a URL:

我有以下代码在 URL 上发出 GET 请求:

$('#searchButton').click(function() {
    $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val());            
});

But the returned result is not always reflected. For example, I made a change in the response that spit out a stack trace but the stack trace did not appear when I clicked on the search button. I looked at the underlying PHP code that controls the ajax response and it had the correct code and visiting the page directly showed the correct result but the output returned by .load was old.

但返回的结果并不总是得到反映。例如,我对吐出堆栈跟踪的响应进行了更改,但是当我单击搜索按钮时,堆栈跟踪没有出现。我查看了控制 ajax 响应的底层 PHP 代码,它有正确的代码,直接访问页面显示正确的结果,但 .load 返回的输出是旧的。

If I close the browser and reopen it it works once and then starts to return the stale information. Can I control this by jQuery or do I need to have my PHP script output headers to control caching?

如果我关闭浏览器并重新打开它,它会工作一次,然后开始返回陈旧的信息。我可以通过 jQuery 控制这个还是需要我的 PHP 脚本输出头来控制缓存?

回答by John Millikin

You have to use a more complex function like $.ajax()if you want to control caching on a per-request basis. Or, if you just want to turn it off for everything, put this at the top of your script:

您必须使用更复杂的功能,例如$.ajax()您想在每个请求的基础上控制缓存。或者,如果您只想将其关闭,请将其放在脚本的顶部:

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

回答by Marshall

Here is an example of how to control caching on a per-request basis

以下是如何基于每个请求控制缓存的示例

$.ajax({
    url: "/YourController",
    cache: false,
    dataType: "html",
    success: function(data) {
        $("#content").html(data);
    }
});

回答by Lou Franco

One way is to add a unique number to the end of the url:

一种方法是在 url 末尾添加一个唯一编号:

$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&uid='+uniqueId());

Where you write uniqueId() to return something different each time it's called.

您在其中编写 uniqueId() 以在每次调用时返回不同的内容。

回答by Gomes

Another approach to put the below line only when require to get data from server,Append the below line along with your ajax url.

仅在需要从服务器获取数据时才放置以下行的另一种方法,将以下行与您的 ajax url 一起附加。

'?_='+Math.round(Math.random()*10000)

'?_='+Math.round(Math.random()*10000)

回答by Sasha

/**
 * Use this function as jQuery "load" to disable request caching in IE
 * Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });
 **/
$.fn.loadWithoutCache = function (){
 var elem = $(this);
 var func = arguments[1];
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data, textStatus, XMLHttpRequest) {
   elem.html(data);
   if(func != undefined){
    func(data, textStatus, XMLHttpRequest);
   }
     }
 });
 return elem;
}

回答by NGRAUPEN

Sasha is good idea, i use a mix.

Sasha 是个好主意,我混合使用。

I create a function

我创建一个函数

LoadWithoutCache: function (url, source) {
    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#" + source).html(data);
            return false;
        }
    });
}

And invoke for diferents parts of my page for example on init:

并调用我页面的不同部分,例如在 init 上:

Init: function (actionUrl1, actionUrl2, actionUrl3) {

初始化:函数(actionUrl1,actionUrl2,actionUrl3){

var ExampleJS= {

var ExampleJS= {

Init: function (actionUrl1, actionUrl2, actionUrl3)           ExampleJS.LoadWithoutCache(actionUrl1, "div1");

ExampleJS.LoadWithoutCache(actionUrl2, "div2"); ExampleJS.LoadWithoutCache(actionUrl3, "div3"); } },

ExampleJS.LoadWithoutCache(actionUrl2, "div2"); ExampleJS.LoadWithoutCache(actionUrl3, "div3"); } },

回答by Xian

This is of particular annoyance in IE. Basically you have to send 'no-cache' HTTP headers back with your response from the server.

这在 IE 中尤其令人烦恼。基本上,您必须将“无缓存”HTTP 标头与来自服务器的响应一起发回。

回答by nickf

For PHP, add this line to your script which serves the information you want:

对于 PHP,将此行添加到提供所需信息的脚本中:

header("cache-control: no-cache");

or, add a unique variable to the query string:

或者,向查询字符串添加一个唯一变量:

"/portal/?f=searchBilling&x=" + (new Date()).getTime()

回答by NickStees

If you want to stick with Jquery's .load() method, add something unique to the URL like a JavaScript timestamp. "+new Date().getTime()". Notice I had to add an "&time=" so it does not alter your pid variable.

如果您想坚持使用 Jquery 的 .load() 方法,请为 URL 添加一些独特的内容,例如 JavaScript 时间戳。“+new Date().getTime()”。请注意,我必须添加一个“&time=”,这样它就不会改变您的 pid 变量。

$('#searchButton').click(function() {
$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&time='+new Date().getTime());            
});

回答by user1545320

Do NOT use timestamp to make an unique URL as for every page you visit is cached in DOM by jquery mobile and you soon run into trouble of running out of memory on mobiles.

不要使用时间戳来创建唯一的 URL,因为您访问的每个页面都被 jquery mobile 缓存在 DOM 中,您很快就会遇到手机内存不足的麻烦。

$jqm(document).bind('pagebeforeload', function(event, data) {
    var url = data.url;
    var savePageInDOM = true;

    if (url.toLowerCase().indexOf("vacancies") >= 0) {
        savePageInDOM = false;
    }

    $jqm.mobile.cache =  savePageInDOM;
})

This code activates before page is loaded, you can use url.indexOf() to determine if the URL is the one you want to cache or not and set the cache parameter accordingly.

此代码在页面加载之前激活,您可以使用 url.indexOf() 来确定该 URL 是否是您要缓存的 URL,并相应地设置缓存参数。

Do not use window.location = ""; to change URL otherwise you will navigate to the address and pagebeforeload will not fire. In order to get around this problem simply use window.location.hash = "";

不要使用 window.location = ""; 更改 URL,否则您将导航到该地址并且 pagebeforeload 不会触发。为了解决这个问题,只需使用 window.location.hash = "";