AJAX入门

同步:点击连接或者提交按钮页面才会跳转,整个页面都会刷新;

异步:点击按钮或者连接只会让页面局部进行刷新;

AJAX的功能:完成页面的局部刷新,不中断用户的体验。

AJAX:异步的javascript和xml(Asynchronous Javascript And XML)

  Asynchronous Javascript(异步的javascript):

    JavaScript中有一个对象XMLHttpRequest可以向服务器异步发送请求;

  XML:

    使用XML作为数据传输的格式;(不论什么语言都可以以XML作为数据传输的一种规范,因为各个语言都支持对xml的解析)

    JSON:javascript的一个对象,它的格式是key,value的键值对。(更为小巧的数据格式)

XMLHttpRequest:

  属性:

    readyState:XMLHttpRequest的状态:

      0(未初始化)对象已经建立,但是尚未初始化(尚未调用open方法)

      1(初始化)对象已经建立,尚未调用send方法

      2(发送数据)send方法已经调用,但是当前的状态及http头未知

      3(数据传送中)已接受部分数据,因为响应及http头不全,这时通过responseBody和responseText获取部分数据会出现错误

      4(完成)数据接受完毕,此时可以通过responseBody和responseText获取完整的回应数据

    onreadystatechange:当XMLHttpRequest状态改变的时候触发一个函数;

    status:获取响应的状态码。eg:200,404...

    responseText:获得响应的文本数据

    responseXML:获得响应的XML数据

  方法:

    open(请求方法,请求路径,是否异步):异步去向服务器发送请求;

    send(请求参数):发送请求;

    setRequestHeader(头信息,头的值):处理POST请求方法的中文问题;

  创建XMLHttpRequest对象:(不同的浏览器及不同的版本获取方式不一样,一般不自行创建,js有些框架已经封装好了直接调用即可,如Jquery)

    IE:将XMLHttpRequest对象封装在一个ActiveXObject组件;

    Firefox:直接就可以创建XMLHttpRequest对象;

    eg:

<script type="text/javascript">
        function createXMLHttpRequest(){
            var xmlHttpRequest;
            try{
                //Firefox,Opera 8.0+,Safari
                xmlHttpRequest = new XMLHttpRequest();
            }catch(e){
                try{
                    //Internet Explorer
                    xmlHttpRequest = new ActiveXObject("Msxm12.XMLHTTP");
                }catch(e){
                    try{
                        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    }catch(e){
                        
                    }
                }
            }
            return xmlHttpRequest;
        }
    </script>
获取XMLHttpRequest最原始的方法

AJAX的入门(最原始的写法)

  AJAX的编写步骤:

    第一步:创建一个异步对象;

    第二步:设置对象状态改变触发一个函数;

    第三步:设置向后台提交的路径

    第四步:发送请求;

  异步请求的两种提交方式:GET&POST:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ajax</title>
</head>
<script type="text/javascript">
    //        获得XMLHttpRequest对象
    function createXMLHttpRequest() {
        var xmlHttpRequest;
        try {
            //Firefox,Opera 8.0+,Safari
            xmlHttpRequest = new XMLHttpRequest();
        } catch (e) {
            try {
                //Internet Explorer
                xmlHttpRequest = new ActiveXObject("Msxm12.XMLHTTP");
            } catch (e) {
                try {
                    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {

                }
            }
        }
        return xmlHttpRequest;
    }
    //        ajax的GET请求
    function ajax_get() {
        //1.创建异步对象
        var xhr = createXMLHttpRequest();
        //2.设置状态改变的监听、回调函数。
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) { //请求发送成功
                if (xhr.status == 200) { //响应也成功
                    //获得响应数据:
                    var data = xhr.responseText;
                    //回写数据:
                    document.getElementById("ajaxdiv").innerHTML = data;
                }
            }
        }
        //3.设置请求路径
        xhr
                .open(
                        "GET",
                        "${pageContext.request.contextPath}/AjaxServlet?username=张三&password=123",
                        true);
        //4.发送请求
        xhr.send(null);//如果没有参数写null,get提交参数拼接在open()中的地址里。
    }
    //        ajax的POST请求
    function ajax_post() {
        //1.创建异步对象
        var xhr = createXMLHttpRequest();
        //2.设置状态改变的监听、回调函数。
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) { //请求发送成功
                if (xhr.status == 200) { //响应也成功
                    //获得响应数据:
                    var data = xhr.responseText;
                    //回写数据:
                    document.getElementById("ajaxdiv").innerHTML = data;
                }
            }
        }
        //3.设置请求路径
        xhr
                .open("POST", "${pageContext.request.contextPath}/AjaxServlet",
                        true);
        //4.设置头信息,解决post无法获得参数的问题
        xhr.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded")
        //5.发送请求
        xhr.send("username=张三&password=123");//如果没有参数写null,get提交参数拼接在open()中的地址里。
    }
</script>
<body>
    <div id="ajaxdiv"
        style=" 300px; height: 300px; border: 1px solid red;"></div>
    <input type="button" onclick="ajax_get()" value="AJAX的GET请求" />
    <input type="button" onclick="ajax_post()" value="AJAX的POST请求" />
</body>
</html>
jsp页面代码
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = new String(request.getParameter("username").getBytes("iso-8859-1"), "utf-8");
        String password = new String(request.getParameter("password").getBytes("iso-8859-1"), "utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("我是get回显的数据:username="+username+";password="+password);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("我是post回显的数据:username="+username+";password="+password);
    }
}
servlet服务端

 JQuery的AJAX(JQuery对AJAX进行了封装,即AJAX框架)

JQuery的AJAX部分方法:

  Jq的对象.load(路径,参数);  --属于POST提交方式,直接将返回的内容赋予该对象,适合简单数据处理;

  $.get(路径,参数,回调函数,数据类型);   ---数据类型如果不传默认当字符串处理,写xml当xml处理,写json当json处理。

  $.post(路径,参数,回调函数,数据类型);

  $.ajax();

  serialize();   -- JQ的AJAX传递参数的时候需要使用的方法;

 1 <html>
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 4 <title>Hello Miss Dang</title>
 5     <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"></script>
 6     <script type="text/javascript">
 7         $(function(){
 8             $("#username").blur(function(){
 9                 var username = $(this).val();
10                 $("#s1").load("${pageContext.request.contextPath}/JQAjaxServlet",{"username":username}); 
11             });
12         });
13     </script>
14 </head>
15 <body>
16     <form>
17         username:<input type="text" id="username" /><span id="s1"></span><br/>
18         password:<input type="password" id="password" />
19         <input id = "reg" type="submit" value="regist" />
20     </form>
21 </body>
22 </html>
load()方法示例
 1 <html>
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 4 <title>Hello Miss Dang</title>
 5     <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"></script>
 6     <script type="text/javascript">
 7         $(function(){
 8             $("#username").blur(function(){
 9                 var username = $(this).val();
10                 //get/post    使用方法相同
11                 $.post("${pageContext.request.contextPath}/JQAjaxServlet",{"username":username},function(data){
12                     //data为服务端回写回来的数据
13                     if (data == 1) {
14                         $("#s1").html("<font color='green'>this username is ok</font>");
15                         $("#reg").attr("disabled",false);
16                     }else{
17                         $("#s1").html("<font color='red'>this username is error</font>");
18                         $("#reg").attr("disabled",true);
19                     }
20                 });
21             });
22         });
23     </script>
24 </head>
25 <body>
26     <form>
27         username:<input type="text" id="username" /><span id="s1"></span><br/>
28         password:<input type="password" id="password" />
29         <input id = "reg" type="submit" value="regist" />
30     </form>
31 </body>
32 </html>
get()/post()方法示例
 1 public class JQAjaxServlet extends HttpServlet {
 2     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 3         System.out.println("i'm get");
 4         String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
 5         response.setContentType("text/html;charset=utf-8");
 6         if (!"zhangsan".equals(username)) {            
 7             response.getWriter().print(1);  //使用get方法实例
 8         }else {
 9             response.getWriter().print(0);  
10         }
11     }
12     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13         System.out.println("i'm post");
14         request.setCharacterEncoding("utf-8");
15         String username = request.getParameter("username");
16         response.setContentType("text/html;charset=utf-8");
17         if (!"zhangsan".equals(username)) {            
18 //            response.getWriter().print("<font color ='green'>用户名可以使用</font>");   //使用load方法示例
19             response.getWriter().print(1);  //使用post方法实例
20         }else {
21 //            response.getWriter().print("<font color ='red'>用户名已经存在</font>");     //使用load方法示例
22             response.getWriter().print(0);  //使用post方法实例
23         }
24     }
25 }
servlet服务端示例
原文地址:https://www.cnblogs.com/laodang/p/9512930.html