AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。
Ajax的核心是XMLHttpRequest对象
1、新建一个JSP页面(ajax.jsp)
<%@ 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> 'ajax.jsp' </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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src = "js/ajax.js"></script>
</head>
<body>
<input type="button" value="点击触发ajax事件(GET)" οnclick="ajaxGet()"/>
<input type="button" value="点击触发ajax事件(POST)" οnclick="ajaxPost()"/>
<lable id ="result"></lable>
</body>
</html>
2、新建ajax.js文件,写入如下创建XMLHttpRequest的代码
function createAjax(){
var ajax = null;
try{
//非IE的创建方式
ajax = new XMLHttpRequest();
}catch(e){
//IE7.0以下的创建方式
//各种IE浏览器创建Ajax对象时传递的参数
var versions=['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Msxml2.XMLHTTP.7.0','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i = 0;i<versions.length;i++){
try{
ajax = new ActiveXObject(versions[i]);
break;
}catch(ex){
}
}
}
return ajax;
}
3、新建一个CheckUserName.java作为处理请求的servlet
package edu.uestc.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;
public class CheckUserName extends HttpServlet {
/**
* Constructor of the object.
*/
public CheckUserName() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//System.out.println("Do Get......");
String username = request.getParameter("userName");
System.out.println(username);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
if ("zsz".equals(username)){
out.println("用户名重复");
}else{
out.println("用户名可用");
}
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
System.out.println(userName+"&&"+password);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
if("zsz".equals(userName)&&"zsz".equals(password)){
out.println("登录成功!");
}else{
out.println("登录失败!");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
在web.xml配置如下:
<servlet>
<servlet-name>CheckUserName</servlet-name>
<servlet-class>edu.uestc.servlet.CheckUserName</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckUserName</servlet-name>
<url-pattern>/servlet/CheckUserName</url-pattern>
</servlet-mapping>
4、在ajax.js文件中写入如下代码,通过ajax来提交一个GET请求
function ajaxGet(){
//创建ajax对象
var ajax = new createAjax();
//创建一个新的http请求,并制定请求的方法和URL
/*
open()方法说明:
XMLHttpRequest.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword); //一般只写前面两个或者三个参数
参数:
bstrMethod:http方法,例如:POST、GET、PUT及PROPFIND。大小写不敏感。
bstrUrl:请求的URL地址,可以为绝对地址也可以为相对地址。
varAsync[可选]:布尔型,指定此请求是否为异步方式,默认为true。如果为真,当状态改变时会调用onreadystatechange属性指定的回调函数。
bstrUser[可选]:如果服务器需要验证,此处指定用户名,如果未指定,当服务器需要验证时,会弹出验证窗口。
bstrPassword[可选]:验证信息中的密码部分,如果用户名为空,则此值将被忽略。
*/
//注:同步请求会阻塞代码,异步请求不会阻塞代码的执行
ajax.open("GET","servlet/CheckUserName?userName=11",true);
//指定当readyState属性改变时的事件处理句柄
ajax.onreadystatechange = function (){
/*readyState说明:
0 (未初始化) 对象已建立,但是尚未初始化(尚未调用open方法)
1 (初始化) 对象已建立,尚未调用send方法
2 (发送数据) send方法已调用,但是当前的状态及http头未知
3 (数据传送中) 已接收部分数据,因为响应及http头不全,这时通过responseBody和responseText获取部分数据会出现错误,
4 (完成) 数据接收完毕,此时可以通过通过responseBody和responseText获取完整的回应数据
*/
if(ajax.readyState==4&&ajax.status==200){
document.getElementById("result").innerHTML = ajax.responseText;
}
}
//如果是GET请求,那么send()里的参数没有任何意义,故下面一行可以省略
ajax.send(null);
}
5、在ajax.js文件中写入如下代码,通过ajax来提交一个POST请求
function ajaxPost(){
//创建ajax对象
var ajax = new createAjax();
//创建一个新的http请求,并制定请求的方法和URL
ajax.open("POST","servlet/CheckUserName");
//只有post方法才用此方法。告诉服务器采用符合URL编码的编码方式
//该方法必须在open()方法之后。(open()方法用来创建链接。因为必须要创建链接后才能发送请求)
ajax.setRequestHeader("content-Type","application/x-www-form-urlencoded");
ajax.onreadystatechange = function (){
if(ajax.readyState==4&&ajax.status==200){
document.getElementById("result").innerHTML = ajax.responseText;
}
}
ajax.send("userName=zsz&&password=zsz");
}