• Ajax技术


    一、概述

    全称:Asynchronous Javascript And XML

    主要用途:实现页面局部刷新

    执行流程:请求-》ajax引擎-》web服务器-》ajax引擎-》页面

    二、XMLHttpRequest对象

    1、创建该对象

    不同版本的浏览器,以不同形式支持XMLHttpRequest对象的创建:

    1. function createXHR(){
    2. const xhr_functions = [
    3. function () {
    4. return new XMLHttpRequest();
    5. },
    6. function () {
    7. return new ActiveXObject("Msxml2.XMLHTTP");
    8. },
    9. function () {
    10. return new ActiveXObject("Microsoft.XMLHTTP")
    11. }
    12. ];
    13. let xhr_obj;
    14. for(let i = 0; i < xhr_functions.length; i++){
    15. try{
    16. xhr_obj = xhr_functions[i];
    17. }catch(e){
    18. continue;
    19. }
    20. break;
    21. }
    22. return xhr_obj;
    23. }

    或者

    1. function createXHR2(){
    2. let xmlHttpRequest;
    3. if(window.XMLHttpRequest){
    4. xmlHttpRequest = new XMLHttpRequest();
    5. }else if(window.ActiveXObject){
    6. try {
    7. xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    8. }catch (e) {
    9. try {
    10. xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    11. }catch (e) {
    12. }
    13. }
    14. }
    15. return xmlHttpRequest;
    16. }

    2、该对象常用方法

    ①创建一个HTTP请求

    1. open(method: string, url: string | URL): void;
    2. 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;

    3、该对象常用属性

    ①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:

    1. Informational responses (100199)
    2. Successful responses (200299)
    3. Redirection messages (300399)
    4. Client error responses (400499)
    5. Server error responses (500599)

    ⑥ readonly statusText: string;

    returns a DOMString containing the response's status message as returned by the HTTP server. 

    三、Ajax应用

    1、打招呼

    创建sayHello.jsp,用于发起Ajax请求:

    1. <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    2. html>
    3. <html>
    4. <head>
    5. <title>打招呼title>
    6. <script type="text/javaScript" src="createRequest.js">script>
    7. head>
    8. <body>
    9. <input type="button" onclick="sayHello()" value="打招呼">
    10. <span id="showHello">span>
    11. body>
    12. <script language="JavaScript">
    13. let xmlRequest;
    14. function sayHello(){
    15. xmlRequest=createXHR();
    16. xmlRequest.onreadystatechange=sayHelloCallBack;
    17. xmlRequest.open("get","returnHello.jsp",true);
    18. xmlRequest.send(null);
    19. }
    20. function sayHelloCallBack(){
    21. if (xmlRequest.readyState==4){
    22. if(xmlRequest.status==200){
    23. let htmlText = xmlRequest.responseText;
    24. document.getElementById("showHello").innerText = htmlText;
    25. }
    26. }
    27. }
    28. script>
    29. html>

    创建returnHello.jsp,用于响应Ajax请求并返回招呼内容:

    1. <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    2. <%="你好啊!"%>

    启动tomcat,在浏览器输入http://localhost:8080/demo1/sayHello.jsp ,点击“打招呼”按钮。

    2、判断用户是否已经注册过

    创建注册页面userRegister.jsp:

    1. <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    2. html>
    3. <html>
    4. <head>
    5. <title>注册title>
    6. <script type="text/javaScript" src="createRequest.js">script>
    7. head>
    8. <body>
    9. <form action="" method="post" name="form1">
    10. 用户名:<input type="text" name="userName" id="userName">
    11. <input type="button" onclick="checkUserName(form1.userName.value)" value="检查用户名"><br>
    12. 密码:<input type="text" name="password"><br>
    13. <input type="submit" value="注册">
    14. form>
    15. <span id="checkMsg">span>
    16. body>
    17. <script language="JavaScript">
    18. let xhr;
    19. function checkUserName(username){
    20. xhr = createXHR();
    21. let url = "userCheck.jsp?username=" + username;
    22. xhr.open("get",url,true);
    23. xhr.onreadystatechange=getCheckResult;
    24. xhr.send(null);
    25. }
    26. function getCheckResult(){
    27. if (xhr.readyState==4){
    28. if (xhr.status==200){
    29. document.getElementById("checkMsg").innerHTML=xhr.responseText;
    30. }
    31. }
    32. }
    33. script>
    34. html>

    创建userCheck.jsp,用于判断用户名是否已注册:

    1. <%@ page import="java.util.Arrays" %>
    2. <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    3. <%
    4. String[] usernames={"a","b","c"};
    5. String username= request.getParameter("username");
    6. Arrays.sort(usernames);
    7. if (Arrays.binarySearch(usernames,username) > -1){
    8. out.println("该用户已经被注册");
    9. }else {
    10. out.println("该用户名可以被注册");
    11. }
    12. %>

     启动tomcat,在浏览器输入http://localhost:8080/demo1/userRegister.jsp

    3、解析XML数据

    XMLHttpRequest对象请求获取XML文件,通过属性responseXML(Document对象)接收XML数据,然后采用DOM的方式解析。

    创建xml文件book.xml:

    1. <allBook>
    2. <book>
    3. <no>1no>
    4. <name>on javaname>
    5. book>
    6. <book>
    7. <no>2no>
    8. <name>最后的讲义name>
    9. book>
    10. <book>
    11. <no>3no>
    12. <name>baobaoyangyuname>
    13. book>
    14. <book>
    15. <no>4no>
    16. <name>springname>
    17. book>
    18. allBook>

    创建book.jsp,用于请求获取book.xml并解析:

    1. <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    2. html>
    3. <html>
    4. <head>
    5. <title>title>
    6. <script type="text/javaScript" src="createRequest.js">script>
    7. head>
    8. <body>
    9. <input type="button" onclick="showBookInfo()" value="获取书的信息"><br>
    10. <span id="bookinfo">span>
    11. body>
    12. <script language="JavaScript">
    13. let xmlRequest;
    14. function showBookInfo(){
    15. xmlRequest=createXHR();
    16. xmlRequest.onreadystatechange=getXMLResult;
    17. xmlRequest.open("get","book.xml",true);
    18. xmlRequest.send(null);
    19. }
    20. function getXMLResult(){
    21. if (xmlRequest.readyState==4){
    22. if(xmlRequest.status==200){
    23. let allBook = xmlRequest.responseXML.getElementsByTagName("book");
    24. let html="";
    25. for (let i =0;ilength;i++){
    26. let book = allBook[i];
    27. let no = book.getElementsByTagName("no")[0].firstChild.nodeValue;
    28. let name = book.getElementsByTagName("name")[0].firstChild.nodeValue;
    29. html = html +"no:"+no+"name:"+name+"
      "
      ;
    30. }
    31. document.getElementById("bookinfo").innerHTML = html;
    32. }
    33. }
    34. }
    35. script>
    36. html>

    4、解决中文乱码问题

    Ajax不支持多种字符集,默认的字符集是UTF-8.

    ①获取请求参数时出现乱码,解决如下:

    1. String username= request.getParameter("username");
    2. username=new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);

    ②获取响应时出现乱码,解决如下:

    保证从服务端返回的数据采用UTF-8即可。

    参考:

    XMLHttpRequest简单介绍 - 知乎

    XMLHttpRequest 详解_杰鹏的梦的博客-CSDN博客_xmlhttprequest

  • 相关阅读:
    JS 事件
    openjudge_2.5基本算法之搜索_1789:算24
    JSP页面中page指令有哪些属性及方法可使用呢?
    概率论与数理统计
    【JavaSE】面向对象——属性和方法
    《网络安全笔记》第十二章:二进制基础
    Python sort 自定义函数排序
    利用FastAPI和OpenAI-Whisper打造高效的语音转录服务
    基于NVIDIA的deepstream进行串行多任务模型开发,DeepStream 多模型组合检测(精)
    栈、队列和数组
  • 原文地址:https://blog.csdn.net/daqi1983/article/details/125802038