---
title: "jQuery.getJSON的缓存问题的解决办法"
author: "mfan"
date: "2011-03-24T15:41:33Z"
tags: ["Ajax", "Cache", "PHP", "jQuery", "百度"]
categories: ["Web前端"]
slug: "jquery-getjson"
draft: false
lastmod: "2011-03-24T15:53:43Z"
id: 974132
url: "https://mfan.iteye.com/blog/974132"
---

今天做测试工作，发现了一个令我费解的问题，jquery的getJson方法在firefox上运行可以得到返回的结果，但是在ie8上测试，竟发现没有发送请求，故不能取到任何返回的结果，经历了一翻周折，找到了百度空间http://hi.baidu.com/fengluolyn/blog/item/0ac6b7130d8985ddf7039e83.html上的解决办法，便摘抄了下来……

1 让每次调用的url都不一样  
方法：在参数中加一个随机数。  
例1：  
jQuery.getJSON("$!{Root}/a/a/s.ashx",{ID:"123456",Name:"john",random:Math.random()},function(responseText){}  
例2：  
"xxx.aspx?randID="+Math.random  
例3：  
"xxx.aspx?randID="+ escape(new Date())  
2 将cache设为False  
$.ajax不缓存版:  
$.ajax({  
type:"GET"  
[url:'test.html']() ,  
cache:false,  
dataType:"html",  
success:function(msg){  
alert(msg);  
}  
});  
3.在labels.html文件的顶部加入以下声明：

&lt;META HTTP-EQUIV="Pragma" CONTENT="no-cache"&gt;

&lt;META HTTP-EQUIV="Expires" CONTENT="-1"&gt;  
4.load函数不仅可以调用HTML，也可以调用script，比如labels.php，可以在php文件里使用header函数：

&lt;?php

header("Cache-Control: no-cache, must-revalidate");

?&gt;  
5 使用post代替get方法。  
使用Post方式需注意：  
设置header的Context-Type为application/x-www-form-urlencode确保服务器知道实体中有参数变量. 通常使用XmlHttpRequest对象的SetRequestHeader("Context-Type","application/x-www- form-urlencoded;")。例：

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
参数是名/值一一对应的键值对,每对值用&号隔开.如 var name=abc&sex=man&age=18，注意var name=update.php?

abc&sex=man&age=18以及var name=?abc&sex=man&age=18的写法都是错误的;  
参数在Send(参数)方法中发送,例： xmlHttp.send(name); 如果是get方式，直接 xmlHttp.send(null);

服务器端请求参数区分Get与Post。如果是get方式则$username = $\_GET\["username"]; 如果是post方式，则$username = $\_POST\["username"];  
6 在服务端加 header("Cache-Control: no-cache, must-reva lidate");  
7 在ajax发送请求前加上 xmlHttpRequest.setRequestHeader("If-Modified-Since","0");  
8 在ajax发送请求前加上 xmlHttpRequest.setRequestHeader("Cache-Control","no-cache");