首页 > 代码库 > ajax入门级实例

ajax入门级实例

 

AJAX = Asynchronous JavaScript And XML(异步 JavaScript 及 XML)。

Ajax 由 HTML、JavaScript? 技术、DHTML 和 DOM 组成,这一杰出的方法可以将笨拙的 Web 界面转化成交互性的 Ajax 应用程序。

今天记下ajax入门级例子,希望和我一样刚入门的可以看懂。

  在AJAX实际运行当中,对于访问XMLHttpRequest(XHR)时并不是一次完成的,而是分别经历了多种状态后取得的结果,对于这种状态在AJAX中共有5种,分别是。
  0 - (未初始化)还没有调用send()方法
  1 - (载入)已调用send()方法,正在发送请求
  2 - (载入完成)send()方法执行完成,
  3 - (交互)正在解析响应内容
  4 - (完成)响应内容解析完成,可以在客户端调用了
  对于上面的状态,其中“0”状态是在定义后自动具有的状态值,而对于成功访问的状态(得到信息)我们大多数采用“4”进行判断。

index.jsp代码如下

 

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
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="http://www.mamicode.com/">   
    <title>My JSP ‘index.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">
    <!--
    <link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css">
    -->
    
    <script>
        function test(){
            //创建XMLHttpRequest对象
            var req;
            //IE7以下是第二种方式,7以上和其他浏览器,如火狐是第一种方式创建XMLHttpRequest
            if(window.XMLHttpRequest){
                req = new XMLHttpRequest();
            }else{
                req = new ActiveXObject("Msxml2.XMLHTTP");
            }
             //处理响应
             req.onreadystatechange = function(){
                 if(4==req.readyState){
                     var result = req.responseText;
                     document.getElementById("div1").innerHTML = result;                     
                 }
             }            
            //发送请求
           req.open("get", "servlet/TestAjaxServlet", true);
           req.send(null);
           alert("heihei");//因为是异步,所以heihei先出现,三秒钟之后出现ajax text
        }
    
    </script>
  </head>
  
  <body>
    <div id=div1></div>
    <input type = "button" value="http://www.mamicode.com/测试ajax" onclick="test()"/>
  </body>
</html>

 

然后创建一个servlet,TestAjaxServlet.jsp

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 TestAjaxServlet extends HttpServlet {
    /**
     * 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("hello ajax");
        try {
            Thread.sleep(3000);//三秒钟之后出现ajax text字样
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        response.getWriter().println("<h1>ajax test </h1>");
    }

    /**
     * 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 {
        doGet(request,response);
    }

}

输入index.jsp地址,

技术分享

点击按钮

技术分享

 

 三秒钟之后出现

技术分享

 因为是异步的所以,先alert才出现ajax test。ajax默认为异步,及参数里面是true.

 

ajax入门级实例