Web階段:第二十章:Ajax請求

什么是Ajax請求?
AJAX即“Asynchronous Javascript And XML”(異步JavaScript和XML),是指一種創(chuàng)建交互式網(wǎng)頁應(yīng)用的網(wǎng)頁開發(fā)技術(shù)。
ajax是一種瀏覽器異步發(fā)起請求。局部更新頁面的技術(shù)。
1、異步發(fā)起請求
2、局部更新頁面

原生Ajax請求的實現(xiàn)(了解)

    <script type="text/javascript">
        function ajaxRequest() {
//     1、我們首先要創(chuàng)建XMLHttpRequest
    var xmlHttpRequest = new XMLHttpRequest();
//     2、調(diào)用open方法設(shè)置請求參數(shù)
    xmlHttpRequest.open("GET", "http://localhost:8080/day17/ajaxServlet?action=javaScriptAjax", true);
//     4、在send方法前綁定onreadystatechange事件,處理請求完成后的操作。
    xmlHttpRequest.onreadystatechange = function(){
    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            alert("響應(yīng)回來啦");
        //     alert("服務(wù)器返回的數(shù)據(jù)是:" + xmlHttpRequest.responseText);
            var jsonObj = JSON.parse( xmlHttpRequest.responseText );
        //     alert( "編號:" + jsonObj.id + ",姓名:" + jsonObj.name );
            document.getElementById("div01").innerHTML = "編號:" + jsonObj.id + ",姓名:" + jsonObj.name;
        }
    }
//     3、調(diào)用send方法發(fā)送請求
    xmlHttpRequest.send();
    alert("這是請求后面的代碼");
    }
 </script>

Jquery中的Ajax請求
$.ajax方法
url 請求的地址
type 請求的方式GET或POST
data 請求的參數(shù)(發(fā)送給服務(wù)器的數(shù)據(jù))
支持兩種格式
一:name=value&name=value
二: { 屬性名:值 }

success 請求成功后響應(yīng)的函數(shù)
dataType 服務(wù)器回傳的數(shù)據(jù)類型
1.text返回純文本、
2.xml、
3.json返回json對象

案例:

// ajax請求
$("#ajaxBtn").click(function(){
    
    $.ajax({
        url:"http://localhost:8080/day17/ajaxServlet",
        type:"GET",
        data:"action=jqueryAjax",
        success:function(msg){
            // 這個success的函數(shù)。一定要有一個參數(shù)。這個參數(shù)是服務(wù)器回傳的數(shù)據(jù)
            alert(msg);
            $("#msg").html("編號是:" + msg.id + ",姓名:" + msg.name);
        },
        dataType:"json"
    });

});

$.get方法和$.post方法
url 請求的地址
data 請求的數(shù)據(jù)
callback 請求成功的回調(diào)函數(shù)
type 響應(yīng)的數(shù)據(jù)類型
案例:

// ajax--get請求
$("#getBtn").click(function(){
    $.get("http://localhost:8080/day17/ajaxServlet",{
            action:"jqueryGet"                   
        },function(msg){
            // msg 請求成功的回調(diào)函數(shù)。參數(shù)msg是用來接收響應(yīng)的數(shù)據(jù)
            $("#msg").html("編號是:" + msg.id + ",姓名:" + msg.name);
        },"json");
    
});

// ajax--post請求
$("#postBtn").click(function(){
    // post請求
    $.post("http://localhost:8080/day17/ajaxServlet","action=jqueryPost",function(msg){
        // msg 請求成功的回調(diào)函數(shù)。參數(shù)msg是用來接收響應(yīng)的數(shù)據(jù)
        $("#msg").html("post請求 編號是:" + msg.id + ",姓名:" + msg.name);
    },"json");
});

$.getJSON方法
url 請求的地址
data 請求的參數(shù)
callback 成功的回調(diào)

getJSON 請求方式固定是GET請求,響應(yīng)的數(shù)據(jù),固定是json格式。
案例:

// ajax--getJson請求
$("#getJSONBtn").click(function(){
    // 調(diào)用
    $.getJSON("http://localhost:8080/day17/ajaxServlet","action=jqueryGetJSON",function(msg){
        $("#msg").html("getJSON請求  編號是:" + msg.id + ",姓名:" + msg.name);
    });
});

表單序列化serialize()
serialize() 方法可以把一個form表單中所有的表單項。都以字符串name=value&name=value的形式進行拼接,省去我們很多不必要的工作。

由于$.get、$.post和getJSON這三個方法的底層都是直接或者間接地使用$.ajax()方法來實現(xiàn)的異步請求的調(diào)用。
案例:

// ajax請求
    $("#submit").click(function(){
        // 把參數(shù)序列化
        // serialize() 方法可以把表單項以name=vlaue&name=value進行拼接。
        var data = $("#form01").serialize();
        alert(data);
        //當(dāng)我們點擊這個按鈕的時候,我們希望把表單中所有的表單項,
        // 以name=value&name=value的信息,進行拼接,然后發(fā)送給服務(wù)器
        $.getJSON("http://localhost:8080/day17/ajaxServlet","action=jquerySerialize&" + data,function(msg){
            $("#msg").html("jquerySerialize  編號是:" + msg.id + ",姓名:" + msg.name);
        });
       
    });

實例:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="pragma" content="no-cache" />
        <meta http-equiv="cache-control" content="no-cache" />
        <meta http-equiv="Expires" content="0" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript" src="script/jquery-1.7.2.js"></script>
        <script type="text/javascript">
            $(function(){
                // ajax請求
                $("#ajaxBtn").click(function(){
                    $.ajax({
                        url : "ajaxServlet", // 請求地址
                        error:function(){   // 請求失敗回調(diào)
                            alert("請求失敗");
                        },
                        success:function(data){ // 請求成功回調(diào)
                            alert( data );
                        },
                        type:"POST",                // 請求的方式
                        dataType:"json",            // 返回的數(shù)據(jù)類型為json對象
                        data:{                        // 請求的參數(shù)
                            action:"jqueryAjax",
                            a:12,
                            date: new Date()
                        }
                    });
                });

                // ajax--get請求
                $("#getBtn").click(function(){
                    $.get(
                        "ajaxServlet",{
                            action:"jqueryGet",
                            a:12,
                            date:new Date()
                        },function(data){alert(data);},"json"
                    );
                });
               
                // ajax--post請求
                $("#postBtn").click(function(){
                    // post請求
                    $.post(
                        "ajaxServlet", // 請求路徑
                        {                // 請求參數(shù)
                            action:"jqueryPost",
                            a:12,
                            date:new Date()
                        },
                        function(data){ alert( data ) },  // 成功的回調(diào)函數(shù)
                        "text"                            // 返回的數(shù)據(jù)類型
                    );
                });

                // ajax--getJson請求
                $("#getJsonBtn").click(function(){
                    // 調(diào)用
                    $.getJSON(
                        "ajaxServlet",         // 請求路徑
                        {                    // 請求參數(shù)
                            action:"jqueryGetJSON",
                            a:12,
                            date:new Date()
                        },
                        function(data){ alert( data ) }  // 成功的回調(diào)函數(shù)       
                    );
                });

                // ajax請求
                $("#submit").click(function(){
                    // 把參數(shù)序列化
                    var data = $("#form01").serialize();
                    alert(data);
                });
               
            });
        </script>
    </head>
    <body>
        <div>
            <button id="ajaxBtn">$.ajax請求</button>
            <button id="getBtn">$.get請求</button>
            <button id="postBtn">$.post請求</button>
            <button id="getJsonBtn">$.getJSON請求</button>
        </div>
        <br/><br/>
        <form id="form01" >
            用戶名:<input name="username" type="text" /><br/>
            密碼:<input name="password" type="password" /><br/>
            下拉單選:<select name="single">
                  <option value="Single">Single</option>
                  <option value="Single2">Single2</option>
            </select><br/>
              下拉多選:
              <select name="multiple" multiple="multiple">
                <option selected="selected" value="Multiple">Multiple</option>
                <option value="Multiple2">Multiple2</option>
                <option selected="selected" value="Multiple3">Multiple3</option>
              </select><br/>
              復(fù)選:
             <input type="checkbox" name="check" value="check1"/> check1
             <input type="checkbox" name="check" value="check2" checked="checked"/> check2<br/>
             單選:
             <input type="radio" name="radio" value="radio1" checked="checked"/> radio1
             <input type="radio" name="radio" value="radio2"/> radio2<br/>
             <input id="submit" type="submit" />
        </form>           
    </body>
</html>

2)AjaxServlet的代碼如下:

package com.atguigu.servlet;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.gson.GsonTest;
import com.google.gson.Gson;

public class AjaxServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    protected void javaScriptAjax(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("ajax請求過來了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用隨機數(shù),可以讓客戶端看到變化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }
    
    protected void jqueryAjax(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("jqueryAjax請求過來了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用隨機數(shù),可以讓客戶端看到變化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }
    
    protected void jqueryGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("jqueryGet請求過來了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用隨機數(shù),可以讓客戶端看到變化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }
    
    protected void jqueryPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("jqueryPost請求過來了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用隨機數(shù),可以讓客戶端看到變化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }
    
    protected void jqueryGetJSON(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("jqueryGetJSON請求過來了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用隨機數(shù),可以讓客戶端看到變化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }

}