52Ajax 禁用缓存

1 Ajax(Asynchronous JavaScript and XML),异步的JavaScript与XML

2 Ajax中的一个重要对象是XMLHttpRequest。

3 使用Ajax准备向服务器端发送请求:

xmlHttpRequest.open("GET", "AjaxServlet", true);

示例

利用ajax 单击按钮刷新div 

(1)

   <input type="button" value="ajax" οnclick="ajaxSubmit();"/>
 
   <div id="div">
(2) JS 代码

注:XMLHTTPRequest对象在IE浏览器中和其他浏览器中实例化方式不一样


<script type="text/javascript">
	var xmlHttpRequest=null;//声明一个空的可以接收XMLHttpRequest对象
	function ajaxSubmit()
	{
		
		
		
		if(window.ActiveXObject)
		{	
			//IE浏览器
			xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
		
		}
		else if(window.XMLHttpRequest)
		{	//除IE以外的其他浏览器 
			xmlHttpRequest=new XMLHttpRequest();
			
		
		}
		if(null!=xmlHttpRequest)
		{
			alert("invoked");
			xmlHttpRequest.open("GET", "/LearnWeb_Test/myAjax1", true)
			//关联好ajax回调函数
			xmlHttpRequest.onreadystatechange=ajaxCallBack;
			//向服务器发送数据
			xmlHttpRequest.send();
		
		}
		
	
	
	}
	
	function ajaxCallBack()
	{
		//回调函数发生4次
		//alert("回调");
		
		if(xmlHttpRequest.readyState==4)
		{
			if(xmlHttpRequest.status==200)
			{
				var responseTest=xmlHttpRequest.responseText;
				document.getElementById("div").innerHTML=responseTest;
			}
		}
	}
	
	
	
	</script>


(3) 服务器端代码

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		System.out.println("invoked");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.print("i miss you father");
		out.flush();
		out.close();
	}


4 禁用页面缓存,通过相应头设置。在服务器端设置


<span style="font-size:24px;">resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");</span>

5 GET与POST的对比


(1) 以GET方式发送请求

var v1=document.getElementById("v1").value;
var v2=document.getElementById("v2").value;			
xmlHttpRequest.open("GET", "/LearnWeb_Test/myAjax1?v1="+v1+"&v2="+v2, true)
			
(2) 以POST方式请求
if (null != xmlHttpRequest)
		{
			
			
			var v1=document.getElementById("v1").value;
			var v2=document.getElementById("v2").value;
			
			xmlHttpRequest.open("POST", "/LearnWeb_Test/myAjax1", true)
			//关联好ajax回调函数
			xmlHttpRequest.onreadystatechange = ajaxCallBack;
			//向服务器发送数据
			xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			// 使用post方式提交,必须要加上如下一行
			xmlHttpRequest.send("v1="+v1+"&v2="+v2);

		}














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值