日期:2014-05-16  浏览次数:20798 次

一个简单的Ajax示例

1.login.jsp

<%@ page language="java"  pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>登录</title>
    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script type="text/javascript" src="login.js"></script>
  </head>
  <body>
	用户名:<input type="text" id="username"/><br />
  	<input type="button" value="校验" onclick="check()"/>
  	<div id="result" style="color:red"></div>
  </body>
</html>

?2.login.js

/* 传统的Ajax */
function check(){
	//获取请求参数
	var username=document.getElementById("username").value;
	//创建XmlHttpRequest对象
	var xmlHttp=createXmlHttpRequest();
	//注册回调函数
	xmlHttp.onreadystatechange=function(){
		if(xmlHttp.readyState==4){
			if(xmlHttp.status==200 || xmlHttp.status==304){
				//获取服务器传回来的数据(文本数据)
				var data=xmlHttp.responseText;
				//显示服务器传回来的数据
				document.getElementById('result').innerHTML=data;
			}
		}
	}
	
	/* get方式 */
	
	//设置连接信息
	//xmlHttp.open('get','servlet/LoginServlet?username='+username+'&timeStamp='+new Date().getTime(),true);
	//发送数据
	//xmlHttp.send(null);
	
	/* post方式 */
	
	//设置连接信息  
	//给地址加上时间戳为了不读取缓存
	xmlHttp.open('post','servlet/LoginServlet?timeStamp='+new Date().getTime(),true);
	//POST需要设置请求头信息
	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//发送数据
	xmlHttp.send('username='+username);
	
}

//XMLHttpRequest对象初始化
function   createXmlHttpRequest(){
   var xmlHttp;
   try{    //Firefox, Opera 8.0+, Safari
           xmlHttp=new XMLHttpRequest();
    }catch (e){
           try{    //Internet Explorer
                  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
            }catch (e){
                  try{
                          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                  }catch (e){}  
           }
    }
   return xmlHttp;
 }

/**********************************************************************************************************/

/* 使用JQuery */
function check2() {
 	//获取提交的数据
	var username = $("#username").val();
	
	/* get方式 */
	/*
	$.get("servlet/LoginServlet", {"username":username}, function (data) {
		//alert(data); //传回来的数据
		$("#result").html(data);  
	});
	*/
	
	/* post方式 */
	$.post("servlet/LoginServlet",{"username":username},function (data){
		$("#result").html(data);
	});
}

?3.LoginServlet

package org.monday.web;

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 LoginServlet extends HttpServlet {

	private static final long serialVersionUID = -899354411233903986L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("请求方式:" + request.getMethod());

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();

		String username = request.getParameter("username");
		
		if (null == username || "".equals(username.trim())) {
			out.print("用户名不能为空");
		} else {
			if ("monday".equals(username.trim())) {
				out.print("该用户名已经存在");
			} else {
				out.print("该用户名可以使用");
			}
		}
	}

}
?

?