使用XMLHttpRequest对象发送请求的基本步骤如下

使用XMLHttpRequest对象发送请求的基本步骤如下:
  1. 为得到XMLHttpRequest对象实例的一个引用,可以创建一个新的实例,也可以访问包含有XMLHttpRequest实例的一个变量。
  2. 告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要把对象的onreadystatechange属性设置为指向JavaScript函数的指针。
  3. 指定请求的属性。XMLHttpRequest对象的open()方法会指定将发出的请求。open()方法取3个参数:一个是指示所用方法(通常是GET或POST)的串;一个是表示目标资源URL的串;一个是Boolean值,指示请求是否是异步的。
  4. 将请求发送给服务器。XMLHttpRequest对象的send()方法把请求发送到指定的目标资源。send()方法接受一个参数,通常是一个串或一个DOM对象。这个参数作为请求体的一部分发送到目标URL。当向send()方法提供参数时,要确保open()中指定的方法是POST。如果没有数据作为请求体的一部分被发送,则使用null。
  这些步骤很直观:你需要XMLHttpRequest对象的一个实例,要告诉它如果状态有变化该怎么做,还要告诉它向哪里发送请求以及如何发送请求,最后还需要指导XMLHttpRequest发送请求。不过,除非你对C或C++很了解,否则可能不明白函数指针(function pointer)是什么意思。
  函数指针与任何其他变量类似,只不过它指向的不是像串、数字、甚至对象实例之类的数据,而是指向一个函数。在JavaScript中,所有函数在内存中都编有地址,可以使用函数名引用。这就提供了很大的灵活性,可以把函数指针作为参数传递给其他函数,或者在一个对象的属性中存储函数指针。
  对于XMLHttpRequest对象,onreadystatechange属性存储了回调函数的指针。当XMLHttpRequest对象的内部状态发生变化时,就会调用这个回调函数。当进行了异步调用,请求就会发出,脚本立即继续处理(在脚本继续工作之前,不必等待请求结束)。一旦发出了请求,对象的readyState属性会经过几个变化。尽管针对任何状态都可以做一些处理,不过你最感兴趣的状态可能是服务器响应结束时的状态。通过设置回调函数,就可以有效地告诉XMLHttpRequest对象:“只要响应到来,就调用这个函数来处理响应。”

例子:一个简单的表单提交,表单数据提交后,会在当前页面显示已经提交的数据信息
<!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>Ajax的简单应用(提交表单)</title>
<script type="text/javascript">
	var xhr;
	var outMsg = "";
	
	//-----------------获得XMLHttpRequest对象---------------------------
	function createXMLHttpRequest() {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
	    }catch(e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e) {
				try {
					xhr = new XMLHttpRequest();
				}catch(e) {
				}
			}
		}
	}
	
	//-------------------------------------------------------------
	function createQUeryString() {
		var userName = document.getElementById("userName").value;
		var queryString = "userName="+userName;
		return queryString;
	}
	
	function doRequest() {
		createXMLHttpRequest();//获得XMLHttpRequest对象
		var queryString = "HelloAjaxJava1?";
		queryString = queryString+createQUeryString();
		xhr.onreadystatechange = handleStateChange;//定义事件处理器,此处理器将在服务器端返回数据时自动被触发执行
		xhr.open("POST",queryString,true);//与服务器连接并发送
		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xhr.send(null);
	}

	
	function handleStateChange() {
		if(xhr.readyState==4) {//4表示数据已经调用完成
			if(xhr.status==200) {//HTTP的状态码
				parseResults();
			}
		}
	}
	
	function parseResults() {
		var responseDiv = document.getElementById("serverResponse");//获得Div对象的元素
		if(responseDiv.hasChildNodes()) {
			responseDiv.removeChild(responseDiv.childNodes[0]);
		}
		var responseText  = document.createTextNode(xhr.responseText);
		responseDiv.appendChild(responseText);
	}
</script>
</head>
<body>
	<h1>Ajax的简单应用(提交表单)</h1>
	<hr><br>
	<form>
		Choose your name:<input type="text" id="userName"/>
		<br>
		<br>
		<input type="reset" value="重置">
		<input type="button" value="提交" id="button1" onclick="javascript:doRequest()">
	</form>
	<br>
	<h2>服务器返回的数据</h2>
	<div id="serverResponse"></div>
</body>
</html>


服务器端代码:
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 HelloAjaxJava1 extends HttpServlet {
	
	protected void processRequest(HttpServletRequest request,HttpServletResponse response,String method)
	throws ServletException,IOException {
		response.setContentType("text/html");
		//获得用户的输入信息
		String userName = request.getParameter("userName");
		//创建回复文本
		String responseText = "userName:"+userName;
		PrintWriter out = response.getWriter();
		out.println(responseText);
		out.close();
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request,response,"POST");
	}
	
}


配置文件web.xml代码:

<?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">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
         <servlet>
		<servlet-name>hello</servlet-name>
		<servlet-class>HelloAjaxJava1</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>hello</servlet-name>
		<url-pattern>/HelloAjaxJava1</url-pattern>
	</servlet-mapping>
</web-app>


你可能感兴趣的:(JavaScript,应用服务器,Ajax,servlet,脚本)