ajax緩存和編碼問題不難解決,下面是解決方法。
編碼問題
默認使用UTF-8,如果一旦發現對象找不到的情況,可能js中輸入了中文,同時js的編碼格式可能為gb2312,可用記事本打開js,另存為 utf-8格式的文檔。
通過XMLHttpRequest獲取的數據,默認的字符編碼是UTF-8,如果前端頁面是GB2312或者其它編碼,顯示獲取的數據就是亂碼。通過XMLHTTPRequest,POST的數據也是UTF-8編碼,如果后臺是GB2312或者其他編碼也會出現亂碼。
Cache緩存問題
由于IE的緩存處理機制問題,每次通過XMLHttpRequest訪問動態頁面返回的總是首次訪問的內容,解決方法有:
1. 客戶端通過添加隨機字符串解決。如:
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發送請求之前加上:
XMLHttpRequest.setRequestHeader("If-Modified-Since","0");
XMLHttpRequest.send(null);