AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 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>
- <script type="text/javascript" src="js/test.js"></script>
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <form >
- 用户名:<input type="text" id="name" /><br/>
- <input type="submit" id="OK" value="校验" />
- </form>
- </body>
- </html>
- function ajaxFunction()
- {
- var xmlHttp=null;
- try
- {
- // Firefox, Opera 8.0+, Safari
- xmlHttp=new XMLHttpRequest();
- }
- catch (e)
- {
- // Internet Explorer
- try
- {
- xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
- }
- catch (e)
- {
- try
- {
- xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
- }
- catch (e)
- {
- alert("您的浏览器不支持AJAX!");
- return false;
- }
- }
- }
- return xmlHttp;
- }
- window.οnlοad=function()
- {
- document.getElementById("OK").οnclick=function()
- {
- //alert("wuuuu");
- /*
- * 1.获取xmlHttpRequest
- * */
- var xmlReq=ajaxFunction();
- /*
- * 4.接手服务器的响应
- *
- * */
- //alert("wuuuu");
- xmlReq.onreadystatechange=function()
- {
- if(xmlReq.readyState==4)
- {
- alert(xmlReq.readyState);
- alert(xmlReq.status);
- if(xmlReq.status==200||xmlReq.status==304)
- {
- alert("wu");
- var data=xmlReq.responseText;
- alert(data);
- }
- }
- }
- /*
- * 2.打开服务器的连接,
- * 第三个参数为true(异步的)
- * 第一个参数:传递方法
- * 第二个方法是路径
- * */
- //alert("路径整的不对啊???怎么改过来???");
- xmlReq.open("get","/Ajax/Demo1",true);
- alert("adsada");
- /*
- * 3.发送数据
- * */
- xmlReq.send(null);
- }
- }
- package cn.com.Demo;
- 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;
- import javax.servlet.jsp.PageContext;
- public class Demo1 extends HttpServlet {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8");
- response.setContentType("text/html; charset=utf-8");
- PrintWriter out=response.getWriter();
- //out.write("OK");
- System.out.println("--------------------------------------");
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request,response);
- }
- }