2012-07-13 164 views
22

我已經安裝了一個應用程序,它在Opera和Firefox上運行得非常棒,但是在Google Chrome瀏覽器中緩存了AJAX請求,並且會顯示過時的數據!阻止Chrome緩存AJAX請求

http://gapps.qk.com.au是應用程序。在Chrome中運行時,它甚至不會發送AJAX請求,但在其他瀏覽器中嘗試時,它始終會執行AJAX請求並返回數據。

是否有任何方法(Apache/PHP/HTML/JS)阻止Chrome執行此操作?

的AJAX調用:

function sendAjax(action,domain,idelement) { 

        //Create the variables 
       var xmlhttp, 
        tmp, 
        params = "action=" + action 
          + "&domain=" + encodeURIComponent(domain) 

        xmlhttp = new XMLHttpRequest(); 
       //Check to see if AJAX request has been sent 
       xmlhttp.onreadystatechange = function() { 
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { 
         $('#'+idelement).html(xmlhttp.responseText); 
        } 
       }; 
       xmlhttp.open("GET", "ajax.php?"+params, true); 
       xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
       //console.log(params); 
       xmlhttp.send(params); 

      } 
sendAjax('gapps','example.com','gapps'); 
+0

什麼是PHP腳本返回的頭文件?確保他們不允許緩存,並返回適當的內容類型。 – mariusnn 2012-07-13 03:30:48

回答

26

瀏覽器的緩存行爲有所不同在不同的設置。您不應該依賴於用戶設置或用戶的瀏覽器。也可以讓瀏覽器忽略標題。

有兩種方法可以防止緩存。

- >將AJAX請求更改爲POST。瀏覽器不緩存POST請求。

- >更好的方法&好方法:使用當前時間戳或任何其他唯一編號爲您的請求添加附加參數。

params = "action=" + action 
     + "&domain=" + encodeURIComponent(domain) 
     + "&preventCache="+new Date(); 
+0

我想這是一個解決方案,但我認爲這是不雅,謝謝! :) – Mattisdada 2012-07-13 04:06:13

+1

只是爲了信息和心靈的平靜。這個解決方案被主要的框架使用,當你說preventCache to ajax時,一個例子就是DOJO。添加一些數字而不是日期 – gaurang171 2012-07-13 04:16:48

+0

真的嗎?這對我來說似乎是一種「哈克」方法,它起作用(很好),但我原以爲會有更好的方法作爲「官方」做法。再次感謝! :) – Mattisdada 2012-07-13 05:50:40

11

另一個替代JavaScript解決方案是使用自定義頁眉: 在PHP它應該是這樣的:

<?php 
    header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");//Dont cache 
    header("Pragma: no-cache");//Dont cache 
    header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");//Make sure it expired in the past (this can be overkill) 
?> 
+0

這是否適用於所有瀏覽器?如果是這樣,這是**多**更優雅的查詢參數黑客... – tjameson 2013-07-16 16:40:47

+1

是的,它適用於所有瀏覽器:) – Mattisdada 2014-03-12 09:24:08

0

下面的一行代碼爲我工作。

$.ajaxSetup({ cache: false });