先附上此次測試的相關頁面名稱及代碼,共有三個文件:web.xml、index.jsp以及放在包 com.ajax.com下的AjaxServerlet.java。
代碼及解釋如下:
(1) index.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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> //1、獲取到xmlhttprequest function getXmlhttp() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; } window.onload = function() { document.getElementById('mybtn').onclick = function() { //1、獲取到xmlhttprequest 對象 var xmlhttp = getXmlhttp(); //2、xmlhttprequest的響應事件 xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //5、操作獲取到的信息 //5.1ajax返回的數據,轉換為javascript對象 // 5.1.1 利用eval實現轉換 var ajaxResult = eval("(" + xmlhttp.responseText + ")"); //5.1.2 利用jquery的方法,對於jQuery.parseJSON(),鍵值必須為雙引號 /* var ajaxResult = jQuery.parseJSON(xmlhttp.responseText); */ alert(ajaxResult) //5.2獲取JavaScript對象的屬性 var age = ajaxResult.age; var name = ajaxResult.name; //5.3獲取到頁面的DIV,並設置內容 var mydiv = document.getElementById("myAjax"); mydiv.innerHTML = "name:" + name + "," + "age:" + age; } } //3、准備獲取ajax請求 //3.1 對於get請求,帶參數的方式,直接在open函數的請求地址帶上參數 xmlhttp.open("POST", "AjaxServerlet", true); //4、發送ajax請求 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); /* *使用post方法提交時,通過send("age=18&name=zhang")傳遞參數 *使用get方法提交時,必須調用send(null) *使用post或get都必須使用調用send() */ xmlhttp.send("age=18&name=zhang"); }; } </script> </head> <body> <button id="mybtn">點擊</button> <div id="myAjax"></div> </body> </html>
xmlhttp.readyState 的取值有0,1,2,3,4。readyState的值每一次改變都會自動調用 onreadystatechange 。
| ReadyState取值 | 描述 |
|
0
|
描述一種"未初始化"狀態;此時,已經創建一個XMLHttpRequest對象,但是還沒有初始化。 |
|
1
|
描述一種"發送"狀態;此時,代碼已經調用了XMLHttpRequest open()方法並且XMLHttpRequest已經准備好把一個請求發送到服務器。 |
|
2
|
描述一種"發送"狀態;此時,已經通過send()方法把一個請求發送到服務器端,但是還沒有收到一個響應。 |
|
3
|
描述一種"正在接收"狀態;此時,已經接收到HTTP響應頭部信息,但是消息體部分還沒有完全接收結束。 |
|
4
|
描述一種"已加載"狀態;此時,響應已經被完全接收。 |
在點擊按鈕后,從創建XMLHttpRequest對象開始到數據交互結束,雖然ReadyState一直在變化,但由於會自動調用 onreadystatechange ,故能在整個過程中實現監聽數據交互的整個流程並做出相應的回應,在這里,當 (xmlhttp.readyState == 4 && xmlhttp.status == 200) ,即數據發送完畢且連接正常時,獲取后台傳過來的數據並顯示到 id 為 myAjax 的 div 中。
當不需要傳遞參數到后台時,可將send()方法中的字符串替換為null,即 send(null),或在 open() 方法中使用 get 方式連接。
(附上 全面剖析XMLHttpRequest對象 鏈接:https://www.cnblogs.com/hyian/p/10675190.html )
(2) web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>AjaxServerlet</servlet-name> <servlet-class>com.ajax.com.AjaxServerlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxServerlet</servlet-name> <url-pattern>/AjaxServerlet</url-pattern> </servlet-mapping> </web-app>
配置servlet的目的是響應 index.jsp 頁面中點擊按鈕出發事件時交由后台java類處理,<url-pattern>標簽中的"/AjaxServerlet"即為前端使用ajax時需要連接的url地址,使用時應去掉“/”。
(3) AjaxServerlet.java
package com.ajax.com; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServerlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String age = request.getParameter("age"); String name = request.getParameter("name"); String personJSON = "{\"name" + "\":\"" + name + "\"," + "\"age" + "\":" + age + "}"; System.out.println(personJSON); response.getWriter().write(personJSON); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
獲取前端傳過來的數據並傳參給前端。
-----end-----
