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" onclick="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",true)
			//关联好ajax回调函数
			xmlHttpRequest.onreadystatechange = ajaxCallBack;
			//向服务器发送数据
			xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			// 使用post方式提交,必须要加上如下一行
			xmlHttpRequest.send("v1="+v1+"&v2="+v2);

		}

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...