解決Ajax緩存(Cache)的問題的方法

2010-08-28 10:55:55來源:西部e網(wǎng)作者:

ajax緩存和編碼問題不難解決,下面是解決方法。

編碼問題

默認(rèn)使用UTF-8,如果一旦發(fā)現(xiàn)對(duì)象找不到的情況,可能js中輸入了中文,同時(shí)js的編碼格式可能為gb2312,可用記事本打開js,另存為 utf-8格式的文檔。

通過XMLHttpRequest獲取的數(shù)據(jù),默認(rèn)的字符編碼是UTF-8,如果前端頁面是GB2312或者其它編碼,顯示獲取的數(shù)據(jù)就是亂碼。通過XMLHTTPRequest,POST的數(shù)據(jù)也是UTF-8編碼,如果后臺(tái)是GB2312或者其他編碼也會(huì)出現(xiàn)亂碼。

Cache緩存問題

由于IE的緩存處理機(jī)制問題,每次通過XMLHttpRequest訪問動(dòng)態(tài)頁面返回的總是首次訪問的內(nèi)容,解決方法有:

1. 客戶端通過添加隨機(jī)字符串解決。如:
var url = 'http://url/';
url += '?temp=' + new Date().getTime();
url += '?temp=' + Math.random();

2. 在HTTP headers禁止緩存。如:

HTTP:
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache, must-revalidate" />
<meta http-equiv="expires" content="Thu, 01 Jan 1970 00:00:01 GMT" />
<meta http-equiv="expires" content="0" />

PHP:
header("Expires: Thu, 01 Jan 1970 00:00:01 GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

ASP:
Response.expires=0
Response.addHeader("pragma","no-cache")
Response.addHeader("Cache-Control","no-cache, must-revalidate")

JSP:
response.addHeader("Cache-Control", "no-cache");
response.addHeader("Expires", "Thu, 01 Jan 1970 00:00:01 GMT");

3. 在XMLHttpRequest發(fā)送請(qǐng)求之前加上:
XMLHttpRequest.setRequestHeader("If-Modified-Since","0");
XMLHttpRequest.send(null);

關(guān)鍵詞:Ajax

贊助商鏈接: