ajax的get請求快取導致無法更新問題

admin發表於2017-02-10
當使用get方式進行url請求的時候,可能會出現這樣的現象。

那就是資料無法更新,而是從快取中讀取老舊的資料,這種現象一般出現在IE瀏覽器中。

程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
function loadXMLDoc() {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  }
  else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById("show").innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET", "demo/ajax/net/demo.aspx", true);
  xmlhttp.send();
}
window.onload = function () {
  var obt = document.getElementById("bt");
  obt.onclick = function () {
    loadXMLDoc();
  }
}
</script>
</head>
<body>
<div>
  <div id="show"></div>
  <input id="bt" type="button" value="檢視效果"/>
</div>
</body>
</html>

上面程式碼的功能是點選一下按鈕獲取一次伺服器的當前時間,但是在IE瀏覽器下會出現問題,那就是隻有第一次是正常的,其他時候的操作會從快取中讀取資料,而不是實時獲取。

解決方案如下:

解決方案一:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>螞蟻部落</title> 
<script>
function loadXMLDoc() {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  }
  else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById("show").innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET", "demo/ajax/net/demo.aspx?rnd="+Math.random(), true);
  xmlhttp.send();
}
window.onload = function () {
  var obt = document.getElementById("bt");
  obt.onclick = function () {
    loadXMLDoc();
  }
}
</script> 
</head> 
<body> 
<div> 
  <div id="show"></div> 
  <input id="bt" type="button" value="檢視效果"/> 
</div> 
</body> 
</html>

上面的方式就是為url請求新增隨機數,這樣就會實時讀取伺服器內容,而不是從快取中讀取。

解決方案二:

可以在後臺程式碼中進行相關設定,以c#程式碼為例子:

[C#] 純文字檢視 複製程式碼
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.Cache.SetNoStore();

相關文章