一个简单的Ajax程序XMLHttpRequest
XMLHttpRequest是Ajax的灵魂,Ajax技术的核心就是异步放松请求,而XMLHttpRequest则是异步放松请求的对象。下面就是一个简单的Ajax程序:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'first.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><script type="text/javascript">//定义XMLHttpRequest对象var request;//完成XMLHttpRequest对象的初始化function createXMLHttpRequest(){if(window.XMLHttpRequest){//DOM 2 浏览器request = new XMLHttpRequest();}else if(window.ActiveXObject){try{request = new ActiveXObject("Msxm12.XMLHTTP");}catch(e){try{request = new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}}}}//下拉值改变时,触发的事件function change(id){//初始化XMLHttpRequestcreateXMLHttpRequest();//设置请求相应的URLvar url = "SelectServlet?id=" + id;//打开与服务器相应连接的地址request.open("POST", url, true);//设置处理响应的回调函数request.onreadystatechange = callback;//发送请求request.send(null);}//定义处理响应的回调函数function callback(){//响应完成且正常alert("1");if(request.readyState==4) {alert("2");if(request.status==200) {alert("3");var selectMsg = request.responseText;alert(selectMsg);document.getElementById("output").innerHTML = selectMsg;}else {alert("发生错误:");}}}</script> </head> <body> <select name="first" id="first" onchange="change(this.value);"> <option value="1" selected="selected">中国</option> <option value="2">美国</option> <option value="3">日本</option> </select> <div id="output"></div> </body></html>?Servlet代码
package com.lbx.servlet;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;@SuppressWarnings("serial")public class SelectServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");String id = request.getParameter("id");System.out.println(id);PrintWriter out = response.getWriter();if(id.equals("1")){out.println("你选择了中国");}if(id.equals("2")){out.println("你选择了美国");}if(id.equals("3")){out.println("你选择了日本");}}}?