AJAX简单实例(GET、POST)

1、GET方式

首先是test.jsp

<script type="text/javascript">
function gethttprequest(){
  	var xmlhttp;
  	try{
  		xmlhttp=new XMLHttpRequest();
  	}catch(e){
  		try{
  			xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
  		}catch(e)
  		{
  			try{
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){}
  		}
  	}
  	return xmlhttp;
}

window.onload=function(){
var xmlhttp;
	document.getElementById("ok").onclick=function(){
	//获取XMLHttpRequest对象
  		
  		xmlhttp=gethttprequest();
  		
  		//与服务器建立连接
  		xmlhttp.open("get","./servlet/Aservlet?timestamp="+new Date().getTime()+"&a=998",true);
  		
  		//发送数据
  		xmlhttp.send("b=666&c=777");
  		//响应服务器
  		
  		xmlhttp.onreadystatechange=function(){
  			alert(xmlhttp.readyState);
  			if(xmlhttp.readyState==4){
  				if(xmlhttp.status==200){
  					var data=xmlhttp.responseText;
  					alert(data);
  				}
  			}
  		}
	}
}
		
</script>
  </head>
  
  <body>
    <form action="" enctype="application/x-www-form-urlencoded">
    	<input type="button" name="ok" id="ok" value="测试"/>
    </form>
  </body>

其次是Aservlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		
		System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
		System.out.println("请求的方式:"+request.getMethod());
		//从test.jsp中的url中接受参数a的值
		System.out.println("参数a的值:"+request.getParameter("a"));
		//从test.jsp中的send中接受参数b,c的值,结果是不能接受到的,因为是GET方式
		System.out.println("参数b的值"+request.getParameter("b"));
		System.out.println("参数b的值"+request.getParameter("c"));
		//给test.jsp页面传送值
		out.println("dddddddddd");
	}

最后是web.xml

<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Aservlet</servlet-name>
    <servlet-class>one.Aservlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Aservlet</servlet-name>
    <url-pattern>/servlet/Aservlet</url-pattern>
  </servlet-mapping>

2、POST方式

基本和GET方式一样,只要作如下修改:

xmlhttp.open("post","./servlet/Aservlet?timestamp="+new Date().getTime()+"&a=998",true);

在调用open函数之后

xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

说明:

使用POST方式,send()可以发送消息,Aservelt.java可以接受到,而GET方式则收不到,即send(null)就可以了。

你可能感兴趣的:(AJAX简单实例(GET、POST))