全称:Asynchronous Javascript And XML
主要用途:实现页面局部刷新
执行流程:请求-》ajax引擎-》web服务器-》ajax引擎-》页面
不同版本的浏览器,以不同形式支持XMLHttpRequest对象的创建:
- function createXHR(){
-
- const xhr_functions = [
- function () {
- return new XMLHttpRequest();
- },
- function () {
- return new ActiveXObject("Msxml2.XMLHTTP");
- },
- function () {
- return new ActiveXObject("Microsoft.XMLHTTP")
- }
- ];
-
- let xhr_obj;
- for(let i = 0; i < xhr_functions.length; i++){
- try{
- xhr_obj = xhr_functions[i];
- }catch(e){
- continue;
- }
- break;
- }
- return xhr_obj;
- }
或者
- function createXHR2(){
-
- let xmlHttpRequest;
- if(window.XMLHttpRequest){
- xmlHttpRequest = new XMLHttpRequest();
- }else if(window.ActiveXObject){
- try {
- xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
- }catch (e) {
- try {
- xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
- }catch (e) {
- }
- }
- }
-
- return xmlHttpRequest;
- }
①创建一个HTTP请求
- open(method: string, url: string | URL): void;
- open(method: string, url: string | URL, async: boolean, username?: string | null, password?: string | null): void;
②发送请求
send(body?: Document | XMLHttpRequestBodyInit | null): void;
③设置请求头
setRequestHeader(name: string, value: string): void;
④获取所有响应头
getAllResponseHeaders(): string;
⑤获取某个响应头
getResponseHeader(name: string): string | null;
⑥取消当前所发出的请求
abort(): void;
①readyState:当前请求的状态
Value State Description
0 UNSENT XMLHttpRequest client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
② onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null;
An event handler that is called whenever the readyState attribute changes.
③ readonly responseText: string;
returns the text received from a server following a request being sent.
④ readonly responseXML: Document | null;
returns a Document containing the HTML or XML retrieved by the request; or null if the request was unsuccessful, has not yet been sent, or if the data can't be parsed as XML or HTML.
⑤ readonly status: number;
returns the numerical HTTP status code of the XMLHttpRequest's response.
HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:
100–199)200–299)300–399)400–499)500–599)⑥ readonly statusText: string;
returns a DOMString containing the response's status message as returned by the HTTP server.
创建sayHello.jsp,用于发起Ajax请求:
- <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
- html>
- <html>
- <head>
- <title>打招呼title>
- <script type="text/javaScript" src="createRequest.js">script>
- head>
- <body>
- <input type="button" onclick="sayHello()" value="打招呼">
-
- <span id="showHello">span>
- body>
- <script language="JavaScript">
- let xmlRequest;
- function sayHello(){
- xmlRequest=createXHR();
- xmlRequest.onreadystatechange=sayHelloCallBack;
- xmlRequest.open("get","returnHello.jsp",true);
- xmlRequest.send(null);
- }
-
- function sayHelloCallBack(){
- if (xmlRequest.readyState==4){
- if(xmlRequest.status==200){
- let htmlText = xmlRequest.responseText;
- document.getElementById("showHello").innerText = htmlText;
- }
- }
- }
- script>
- html>
创建returnHello.jsp,用于响应Ajax请求并返回招呼内容:
- <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
- <%="你好啊!"%>
启动tomcat,在浏览器输入http://localhost:8080/demo1/sayHello.jsp ,点击“打招呼”按钮。
创建注册页面userRegister.jsp:
- <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
- html>
- <html>
- <head>
- <title>注册title>
- <script type="text/javaScript" src="createRequest.js">script>
- head>
- <body>
- <form action="" method="post" name="form1">
- 用户名:<input type="text" name="userName" id="userName">
- <input type="button" onclick="checkUserName(form1.userName.value)" value="检查用户名"><br>
- 密码:<input type="text" name="password"><br>
- <input type="submit" value="注册">
- form>
- <span id="checkMsg">span>
- body>
- <script language="JavaScript">
- let xhr;
- function checkUserName(username){
- xhr = createXHR();
- let url = "userCheck.jsp?username=" + username;
- xhr.open("get",url,true);
- xhr.onreadystatechange=getCheckResult;
- xhr.send(null);
- }
-
- function getCheckResult(){
- if (xhr.readyState==4){
- if (xhr.status==200){
- document.getElementById("checkMsg").innerHTML=xhr.responseText;
- }
- }
- }
- script>
- html>
创建userCheck.jsp,用于判断用户名是否已注册:
- <%@ page import="java.util.Arrays" %>
- <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
- <%
- String[] usernames={"a","b","c"};
- String username= request.getParameter("username");
- Arrays.sort(usernames);
- if (Arrays.binarySearch(usernames,username) > -1){
- out.println("该用户已经被注册");
- }else {
- out.println("该用户名可以被注册");
- }
- %>
启动tomcat,在浏览器输入http://localhost:8080/demo1/userRegister.jsp
XMLHttpRequest对象请求获取XML文件,通过属性responseXML(Document对象)接收XML数据,然后采用DOM的方式解析。
创建xml文件book.xml:
- <allBook>
- <book>
- <no>1no>
- <name>on javaname>
- book>
- <book>
- <no>2no>
- <name>最后的讲义name>
- book>
- <book>
- <no>3no>
- <name>baobaoyangyuname>
- book>
- <book>
- <no>4no>
- <name>springname>
- book>
- allBook>
创建book.jsp,用于请求获取book.xml并解析:
- <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
- html>
- <html>
- <head>
- <title>书title>
- <script type="text/javaScript" src="createRequest.js">script>
- head>
- <body>
- <input type="button" onclick="showBookInfo()" value="获取书的信息"><br>
-
- <span id="bookinfo">span>
- body>
- <script language="JavaScript">
- let xmlRequest;
- function showBookInfo(){
- xmlRequest=createXHR();
- xmlRequest.onreadystatechange=getXMLResult;
- xmlRequest.open("get","book.xml",true);
- xmlRequest.send(null);
- }
-
- function getXMLResult(){
- if (xmlRequest.readyState==4){
- if(xmlRequest.status==200){
- let allBook = xmlRequest.responseXML.getElementsByTagName("book");
- let html="";
- for (let i =0;i
length;i++){ - let book = allBook[i];
- let no = book.getElementsByTagName("no")[0].firstChild.nodeValue;
- let name = book.getElementsByTagName("name")[0].firstChild.nodeValue;
- html = html +"no:"+no+"name:"+name+"
"; - }
- document.getElementById("bookinfo").innerHTML = html;
- }
- }
- }
- script>
- html>
Ajax不支持多种字符集,默认的字符集是UTF-8.
①获取请求参数时出现乱码,解决如下:
- String username= request.getParameter("username");
- username=new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
②获取响应时出现乱码,解决如下:
保证从服务端返回的数据采用UTF-8即可。