欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ajax post和get两种提交方式

程序员文章站 2022-07-07 21:39:01
...
最近看ajax基础教程,学者敲书上的代码。在这里记录一下,方便以后用时可以查阅。

GetAndPostExample.html的源码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

	<script type="text/javascript">
		var xmlHttp ;
		function createXMLHttpRequest(){
			if(window.ActiveXObject){
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} else if(window.XMLHttpRequest){
				xmlHttp = new XMLHttpRequest();
			}
		}
		
		function createQueryString(){
			var firstName = document.getElementById("firstName").value;
			var middleName = document.getElementById("middleName").value;
			var birthday = document.getElementById("birthday").value;
			
			var queryString = "firstName="+firstName+"&middleName="+middleName
			+"&birthday="+birthday;
			
			return queryString;
		}
		
		function doRequestUsingGET(){
			createXMLHttpRequest();
			var queryString  = "GetAndPostExample?";
			queryString = queryString + createQueryString()+
			"&timestamp="+ new Date().getTime();
			xmlHttp.onreadystatechange = handleStateChange;
			xmlHttp.open("GET",queryString,true);
			xmlHttp.send(null);
		}
		
		function doRequestUsingPOST(){
			createXMLHttpRequest();
			var url = "GetAndPostExample?timestampe=" + new Date().getTime();
			xmlHttp.open("POST",url,true);
			xmlHttp.onreadystatechange = handleStateChange;
			xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
			
			var queryString  = createQueryString();
			xmlHttp.send(queryString);
		}
		
		function handleStateChange(){
		
			if(xmlHttp.readyState == 4){
				if(xmlHttp.status == 200) {
					parseResults();
				}
			}
		}
		
		function parseResults(){
		
			var responseDiv = document.getElementById("serverResponse");
			if (responseDiv.hasChildNodes()){
				responseDiv.removeChild(responseDiv.childNodes[0]);
			}
			
			var responseText = document.createTextNode(xmlHttp.responseText);
			responseDiv.appendChild(responseText);
		}
	</script>
</head>
<body>
	<table>
		<tbody>
			<tr>
				<td>firstName</td>
				<td><input type="text" id="firstName"/></td>
			</tr>
			
			<tr>
				<td>middleName</td>
				<td><input type="text" id="middleName"/></td>
			</tr>
			
			<tr>
				<td>birthday</td>
				<td><input type="text" id="birthday"/></td>
			</tr>
		</tbody>
	</table>
	
	<form action="#">
		<input type="button" value="Send Parameter use GET" onclick="doRequestUsingGET();"/>
		<br/><br/>
		
		<input type="button" value="Send Parameter use POST" onclick="doRequestUsingPOST();"/>
		
	</form>
	
	<br/><br/>
	<h2>server response:</h2>
		<div id="serverResponse">
		</div>
</body>
</html>


上面的请求将调用服务器端得GetAndPostExample这个servlet。
GetAndPostExample.java代码如下:
package ajaxbook.chap3;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetAndPostExample extends HttpServlet{
	
	
	protected void processRequest(HttpServletRequest req,
			HttpServletResponse res,String method) throws IOException{
		res.setContentType("text/xml");
		
		String firstName = req.getParameter("firstName");
		String middleName = req.getParameter("middleName");
		String birthday = req.getParameter("birthday");
		
		StringBuilder sBuilder =  new StringBuilder();
		sBuilder.append("Hello ").append(firstName).append(" ").append(middleName);
		sBuilder.append(". Your birthday is ").
		append(birthday).append(". Your request method is ").append(method).append(" .");
		
		PrintWriter pw = res.getWriter();
		pw.write(sBuilder.toString());
		
		pw.close();		
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		System.out.println("the get method");
		processRequest(req,res,"GET");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		System.out.println("the post method");
		processRequest(req,res,"POST");
	}
	
}



开始时遇到一点小问题,客户端请求不到该servlet。后面还是想起来了,要在web.xml文件中配置servlet和请求路径。看来是用struts用多了,都忘了最基本的了。
web.xml中要配置请求的servlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	
	
	<servlet>
		<servlet-name>GetAndPostExample</servlet-name>
		<servlet-class>ajaxbook.chap3.GetAndPostExample</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>GetAndPostExample</servlet-name>
		<url-pattern>/GetAndPostExample</url-pattern>
	</servlet-mapping>
	
	
</web-app>