微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);

		}

原文地址:https://www.jb51.cc/ajax/164286.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐