• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

异步通信技术AJAX | JSON、XML的数据交换

武飞扬头像
@每天都要敲代码
帮助1

目录

一:快速搞定AJAX(第二篇)

1、JS中如何创建和访问JSON对象

2、基于JSON的数据交换(重点)

3、基于XML的数据交换(了解)


一:快速搞定AJAX(第二篇)

1、JS中如何创建和访问JSON对象

(1)在javascript语言中怎么创建一个json对象,语法是什么?

"属性名" : 属性值,  "属性名" : 属性值.........的格式!

注意:属性值的数据类型随意;可能是数字,可能是布尔类型,可能是字符串,可能是数组,也可能是一个json对象.....

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>Title</title>
  6.  
    </head>
  7.  
    <body>
  8.  
    <script type="text/javascript">
  9.  
    // 先创建一个JSON对象
  10.  
    var address = {
  11.  
    "city" :"安徽",
  12.  
    "street" : "城关镇",
  13.  
    "zipcode" : "123"
  14.  
    }
  15.  
     
  16.  
    // 另一个JSON对象
  17.  
    var user = {
  18.  
    "usercode" : 111,
  19.  
    "username" : "zhangsan",
  20.  
    "sex" : true,
  21.  
    "age" : 20,
  22.  
    "aihao" : ["抽烟","喝酒","烫头"],
  23.  
    "addr" : address
  24.  
    }
  25.  
     
  26.  
    // 上面就等价于
  27.  
    var user = {
  28.  
    "usercode" : 111,
  29.  
    "username" : "zhangsan",
  30.  
    "sex" : true,
  31.  
    "age" : 20,
  32.  
    "aihao" : ["抽烟","喝酒","烫头"],
  33.  
    "addr" :{
  34.  
    "usercode" : 111,
  35.  
    "username" : "zhangsan",
  36.  
    "sex" : true,
  37.  
    "age" : 20,
  38.  
    "aihao" : ["抽烟","喝酒","烫头"],
  39.  
    "addr" : address}
  40.  
    }
  41.  
     
  42.  
     
  43.  
    </script>
  44.  
    </body>
  45.  
    </html>
学新通

(2)如何去访问json对象?主要有两种方式:

第一种方式:使用 .属性名 的方式

第二种方式:使用 ["属性名"] 的方式

  1.  
    // 第一种方式
  2.  
    console.log(address.city);
  3.  
    console.log(user.addr.street);
  4.  
    for (var i = 0;i<user.aihao.length;i ){
  5.  
    console.log(user.aihao[i]);
  6.  
    }
  7.  
    // 第二种方式
  8.  
    console.log(address["city"]);
  9.  
    console.log(user["sex"]?"男":"女");

2、基于JSON的数据交换(重点)

(1)将JSON格式字符串转换为JSON对象

我们知道从后端java程序中响应回来的是字符串(json格式的字符串),那么你怎么把json格式的字符串转换成json对象呢?主要有两种方式:

JSON格式的字符串

  1.  
     
  2.  
    var fromJavaServerJsonStr = "{"usercode" : 111, "age" : 20}";
  3.  
    // \是转义字符的作用,防止与外面的双引号冲突
  4.  
    var fromJavaServerJsonStr = "{\"usercode\" : 111, \"age\" : 20}";

第一种方式:使用eval函数

  1.  
    window.eval("var jsonobj1 = " fromJavaServerJsonStr);
  2.  
    // 进行访问
  3.  
    alert(jsonobj1.usercode); // 111

第二种方式:调用javascript语言中的内置对象JSON的一个方法parse。

  1.  
    var jsonobj2 = JSON.parse(fromJavaServerJsonStr);
  2.  
    alert(jsonobj2.age); // 20

(2)基于JSON的数据交换

①对于后端,不在写html的代码,只负责把数据以JSON格式的字符串返回;后端变轻松了。

②对于前端,负责把接收到的JSON格式的字符串转换成JSON对象,并完成拼串的操作;前端变复杂了。

③整体上,后端只会出现后端的代码,前端只会出现前端的代码,便于维护!

第一种方式:对于静态的字符串

后端得到静态的数据,不在拼接HTML程序(写前端代码),只负责把数据响应回去,拼接成JSON格式的字符串

  1.  
    StringBuilder html = new StringBuilder();
  2.  
    html.append("<tr>");
  3.  
    html.append("<td>1</td>");
  4.  
    html.append("<td>王五</td>");
  5.  
    html.append("<td>20</td>");
  6.  
    html.append("<td>北京大兴区</td>");
  7.  
    html.append("</tr>");
  8.  
    html.append("<tr>");
  9.  
    html.append("<td>2</td>");
  10.  
    html.append("<td>李四</td>");
  11.  
    html.append("<td>22</td>");
  12.  
    html.append("<td>北京海淀区</td>");
  13.  
    html.append("</tr>");
  14.  
     
  15.  
    // --------------------------------------------修改为
  16.  
     
  17.  
    // 将以上程序拼接HTML,换成拼接JSON格式的字符串。
  18.  
    String jsonStr = "[{\"name\":\"王五\",\"age\":20,\"addr\":\"北京大兴区\"}, {\"name\":\"李四\",\"age\":22,\"addr\":\"北京海淀区\"}]";
  19.  
    // 响应JSON格式的字符串给前端。
  20.  
    out.print(jsonStr);
学新通

前端不在直接拿后端拼好的字符串格式,而是拿到JSON格式的字符串进行处理,在前端进行拼串

  1.  
    document.getElementById("stutbody").innerHTML = this.responseText
  2.  
    // -----------------------------------修改为
  3.  
    // 将json格式的字符串转换成json对象
  4.  
    var stuList = JSON.parse(this.responseText);
  5.  
    // 是一个数组,并且数组中有多个学生数据
  6.  
    var html = ""
  7.  
    for (var i = 0; i < stuList.length; i ) {
  8.  
    var stu = stuList[i]
  9.  
    html = "<tr>"
  10.  
    html = "<td>" (i 1) "</td>"
  11.  
    html = "<td>" stu.name "</td>"
  12.  
    html = "<td>" stu.age "</td>"
  13.  
    html = "<td>" stu.addr "</td>"
  14.  
    html = "</tr>"
  15.  
    }
  16.  
    document.getElementById("stutbody").innerHTML = html
学新通

第二种方式:连接数据库动态拼接JSON字符串

①创建数据库表

学新通

②后端连接数据库,拼接成JSON格式的字符串

  1.  
    package com.bjpowernode.javaweb.ajax;
  2.  
     
  3.  
    import javax.servlet.ServletException;
  4.  
    import javax.servlet.annotation.WebServlet;
  5.  
    import javax.servlet.http.HttpServlet;
  6.  
    import javax.servlet.http.HttpServletRequest;
  7.  
    import javax.servlet.http.HttpServletResponse;
  8.  
    import java.io.IOException;
  9.  
    import java.io.PrintWriter;
  10.  
    import java.sql.*;
  11.  
     
  12.  
    /**
  13.  
    * @Author:朗朗乾坤
  14.  
    * @Package:com.bjpowernode.javaweb.ajax
  15.  
    * @Project:ajax
  16.  
    * @name:AjaxRequest5Servlet
  17.  
    * @Date:2022/12/6 17:13
  18.  
    */
  19.  
    @WebServlet("/ajaxrequest5")
  20.  
    public class AjaxRequest5Servlet extends HttpServlet {
  21.  
    @Override
  22.  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
  23.  
    throws ServletException, IOException {
  24.  
    // 响应到浏览器
  25.  
    response.setContentType("text/html;charset=UTF-8");
  26.  
    PrintWriter out = response.getWriter();
  27.  
     
  28.  
    // 用于拼接成JSON的字符串
  29.  
    StringBuffer json = new StringBuffer();
  30.  
    String jsonobj = "";
  31.  
    // 连接数据库
  32.  
    Connection conn = null;
  33.  
    PreparedStatement ps = null;
  34.  
    ResultSet rs = null;
  35.  
    try {
  36.  
    // 注册驱动
  37.  
    Class.forName("com.mysql.jdbc.Driver");
  38.  
    // 获取连接
  39.  
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "123");
  40.  
    // 获取预编译的数据库操作对象
  41.  
    String sql = "select name,age,addr from t_student ";
  42.  
    ps = conn.prepareStatement(sql);
  43.  
    // 执行sql
  44.  
    rs = ps.executeQuery();
  45.  
    // 处理查询结果集
  46.  
    json.append("[");
  47.  
    while (rs.next()) { // 每循环一次,就拼接一次
  48.  
    String name = rs.getString("name");
  49.  
    String age = rs.getString("age");
  50.  
    String addr = rs.getString("addr");
  51.  
    // 拼成JSON格式的字符串对象,每次循环拼接的格式如下
  52.  
    // {"name":" 王五 ","age": 20 ,"addr":" 北京大兴区 "},
  53.  
    json.append(" {\"name\":\"");
  54.  
    json.append(name);
  55.  
    json.append("\",\"age\":");
  56.  
    json.append(age);
  57.  
    json.append(",\"addr\":\"");
  58.  
    json.append(addr);
  59.  
    json.append("\"},");
  60.  
    }
  61.  
    // 上面这样拼接,最后一个JSON格式的对象会多一个逗号,所以进行截串
  62.  
    jsonobj = json.substring(0,json.length()-1) "]";
  63.  
     
  64.  
    } catch (ClassNotFoundException e) {
  65.  
    e.printStackTrace();
  66.  
    } catch (SQLException e) {
  67.  
    e.printStackTrace();
  68.  
    } finally {
  69.  
    // 释放资源
  70.  
    if (rs != null) {
  71.  
    try {
  72.  
    rs.close();
  73.  
    } catch (SQLException e) {
  74.  
    e.printStackTrace();
  75.  
    }
  76.  
    }
  77.  
    if (ps != null) {
  78.  
    try {
  79.  
    ps.close();
  80.  
    } catch (SQLException e) {
  81.  
    e.printStackTrace();
  82.  
    }
  83.  
    }
  84.  
    if (conn != null) {
  85.  
    try {
  86.  
    conn.close();
  87.  
    } catch (SQLException e) {
  88.  
    e.printStackTrace();
  89.  
    }
  90.  
    }
  91.  
    }
  92.  
    // 响应JSON格式的字符串给前端
  93.  
    out.print(jsonobj);
  94.  
    }
  95.  
    }
学新通

③前端对JSON格式的字符串进行处理,然后拼串

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>发送AJAX请求,显示学生列表</title>
  6.  
    </head>
  7.  
    <body>
  8.  
    <script type="text/javascript">
  9.  
    window.onload = function () {
  10.  
    document.getElementById("btn").onclick = function () {
  11.  
    // 1.创建核心对象
  12.  
    var xhr = new XMLHttpRequest();
  13.  
    // 2.注册回调函数
  14.  
    xhr.onreadystatechange = function () {
  15.  
    if (this.readyState == 4) {
  16.  
    if (this.status == 200) {
  17.  
    //document.getElementById("mybody").innerHTML = this.responseText
  18.  
    // 将json格式的字符串转换成json对象
  19.  
    var stuList = JSON.parse(this.responseText)
  20.  
    // 是一个数组,并且数组中有多个学生数据
  21.  
    var html = ""
  22.  
    for (var i = 0; i < stuList.length; i ) {
  23.  
    var stu = stuList[i]
  24.  
    html = "<tr>"
  25.  
    html = "<td>" (i 1) "</td>"
  26.  
    html = "<td>" stu.name "</td>"
  27.  
    html = "<td>" stu.age "</td>"
  28.  
    html = "<td>" stu.addr "</td>"
  29.  
    html = "</tr>"
  30.  
    }
  31.  
    document.getElementById("mybody").innerHTML = html
  32.  
    } else {
  33.  
    alert(this.status)
  34.  
    }
  35.  
    }
  36.  
    }
  37.  
    // 3.开启通道
  38.  
    xhr.open("GET", "/ajax/ajaxrequest5", true)
  39.  
    // 4.发送请求
  40.  
    xhr.send()
  41.  
    }
  42.  
    }
  43.  
    </script>
  44.  
     
  45.  
    <input type="button" value="显示学员列表" id="btn">
  46.  
    <table border="1px" width="50%">
  47.  
    <tr>
  48.  
    <th>序号</th>
  49.  
    <th>姓名</th>
  50.  
    <th>年龄</th>
  51.  
    <th>住址</th>
  52.  
    </tr>
  53.  
    <!--具体的内容需要连接数据库动态获取,为了便于操作,写一个tbody-->
  54.  
    <tbody id="mybody">
  55.  
    <!--具体内容响应在这里-->
  56.  
    </tbody>
  57.  
     
  58.  
    </table>
  59.  
     
  60.  
     
  61.  
    </body>
  62.  
    </html>
学新通

④效果展示,点击按钮

学新通

(3)fastjson组件优化代码

从上面代码来看,拼接JSON格式的字符串太痛苦,可以使用阿里巴巴的fastjson组件,它可以将java对象转换成json格式的字符串

😊测试通过fastjson对象转换为JSON格式字符串

①引入jar包,并在项目依赖中也要引入

学新通

学新通

②创建一个User类 

  1.  
    package com.bjpowernode.javaweb.fastjson;
  2.  
     
  3.  
    public class User {
  4.  
    private String id;
  5.  
    private String username;
  6.  
    private int age;
  7.  
     
  8.  
    public User() {
  9.  
    }
  10.  
     
  11.  
    public User(String id, String username, int age) {
  12.  
    this.id = id;
  13.  
    this.username = username;
  14.  
    this.age = age;
  15.  
    }
  16.  
     
  17.  
    public String getId() {
  18.  
    return id;
  19.  
    }
  20.  
     
  21.  
    public void setId(String id) {
  22.  
    this.id = id;
  23.  
    }
  24.  
     
  25.  
    public String getUsername() {
  26.  
    return username;
  27.  
    }
  28.  
     
  29.  
    public void setUsername(String username) {
  30.  
    this.username = username;
  31.  
    }
  32.  
     
  33.  
    public int getAge() {
  34.  
    return age;
  35.  
    }
  36.  
     
  37.  
    public void setAge(int age) {
  38.  
    this.age = age;
  39.  
    }
  40.  
    }
学新通

③进行测试;JSON类中的方法都是静态的方法,直接调用即可

  1.  
    package com.bjpowernode.javaweb.fastjson;
  2.  
     
  3.  
    import com.alibaba.fastjson.JSON;
  4.  
     
  5.  
    import java.util.ArrayList;
  6.  
    import java.util.List;
  7.  
     
  8.  
     
  9.  
    public class FastjsonTest {
  10.  
    public static void main(String[] args) {
  11.  
    // 创建一个User类型的对象
  12.  
    User user1 = new User("111", "zhangsan", 20);
  13.  
    // 将以上的User对象转换成json格式的字符串
  14.  
    // JSON类中的方法都是静态的方法,直接调用即可。
  15.  
    String jsonSTr = JSON.toJSONString(user1);
  16.  
    System.out.println(jsonSTr);
  17.  
     
  18.  
    // 在创建一个对象,放入集合当中,看会不会转换成JSON格式的数组
  19.  
    User user2 = new User("222", "lisi", 20);
  20.  
    // 创建一个集合
  21.  
    ArrayList<User> userList = new ArrayList<>();
  22.  
    // 把数据添加进去
  23.  
    userList.add(user1);
  24.  
    userList.add(user2);
  25.  
    // 转换成JSON对象的数组
  26.  
    String jsonStr2 = JSON.toJSONString(userList);
  27.  
    System.out.println(jsonStr2);
  28.  
     
  29.  
    }
  30.  
    }
学新通

④测试结果如下

学新通

😊通过fastjson组件替换手动拼串成JSON格式的对象

思考:我们从数据库中取出来的数据都是零散的,所以我们每次取到的数据封装成一个Student对象,然后在把这个对象放入一个集合当中;最终把通过这个集合调用JSON.toJSONString方法,把数据转换成JSON格式的对象!

①Student类

  1.  
    package com.bjpowernode.javaweb.bean;
  2.  
     
  3.  
     
  4.  
    public class Student {
  5.  
    private String name;
  6.  
    private int age;
  7.  
    private String addr;
  8.  
     
  9.  
    public Student() {
  10.  
    }
  11.  
     
  12.  
    public Student(String name, int age, String addr) {
  13.  
    this.name = name;
  14.  
    this.age = age;
  15.  
    this.addr = addr;
  16.  
    }
  17.  
     
  18.  
    public String getName() {
  19.  
    return name;
  20.  
    }
  21.  
     
  22.  
    public void setName(String name) {
  23.  
    this.name = name;
  24.  
    }
  25.  
     
  26.  
    public int getAge() {
  27.  
    return age;
  28.  
    }
  29.  
     
  30.  
    public void setAge(int age) {
  31.  
    this.age = age;
  32.  
    }
  33.  
     
  34.  
    public String getAddr() {
  35.  
    return addr;
  36.  
    }
  37.  
     
  38.  
    public void setAddr(String addr) {
  39.  
    this.addr = addr;
  40.  
    }
  41.  
    }
学新通

②后端代码进行优化

  1.  
    package com.bjpowernode.javaweb.ajax;
  2.  
     
  3.  
    import com.alibaba.fastjson.JSON;
  4.  
    import com.bjpowernode.javaweb.bean.Student;
  5.  
     
  6.  
    import javax.servlet.ServletException;
  7.  
    import javax.servlet.annotation.WebServlet;
  8.  
    import javax.servlet.http.HttpServlet;
  9.  
    import javax.servlet.http.HttpServletRequest;
  10.  
    import javax.servlet.http.HttpServletResponse;
  11.  
    import java.io.IOException;
  12.  
    import java.io.PrintWriter;
  13.  
    import java.sql.*;
  14.  
    import java.util.ArrayList;
  15.  
    import java.util.List;
  16.  
     
  17.  
    /**
  18.  
    * @Author:朗朗乾坤
  19.  
    * @Package:com.bjpowernode.javaweb.ajax
  20.  
    * @Project:ajax
  21.  
    * @name:AjaxRequest5Servlet
  22.  
    * @Date:2022/12/6 17:13
  23.  
    */
  24.  
    @WebServlet("/ajaxrequest5")
  25.  
    public class AjaxRequest5Servlet extends HttpServlet {
  26.  
    @Override
  27.  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
  28.  
    throws ServletException, IOException {
  29.  
    // 响应到浏览器
  30.  
    response.setContentType("text/html;charset=UTF-8");
  31.  
    PrintWriter out = response.getWriter();
  32.  
     
  33.  
    // 用于拼接成JSON的字符串
  34.  
    // StringBuffer json = new StringBuffer();
  35.  
    String jsonobj = "";
  36.  
    // 连接数据库
  37.  
    Connection conn = null;
  38.  
    PreparedStatement ps = null;
  39.  
    ResultSet rs = null;
  40.  
    try {
  41.  
    // 注册驱动
  42.  
    Class.forName("com.mysql.jdbc.Driver");
  43.  
    // 获取连接
  44.  
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "123");
  45.  
    // 获取预编译的数据库操作对象
  46.  
    String sql = "select name,age,addr from t_student ";
  47.  
    ps = conn.prepareStatement(sql);
  48.  
    // 执行sql
  49.  
    rs = ps.executeQuery();
  50.  
    // 处理查询结果集
  51.  
    /*json.append("[");
  52.  
    while (rs.next()) { // 每循环一次,就拼接一次
  53.  
    String name = rs.getString("name");
  54.  
    String age = rs.getString("age");
  55.  
    String addr = rs.getString("addr");
  56.  
    // 拼成JSON格式的字符串对象,每次循环拼接的格式如下
  57.  
    // {"name":" 王五 ","age": 20 ,"addr":" 北京大兴区 "},
  58.  
    json.append(" {\"name\":\"");
  59.  
    json.append(name);
  60.  
    json.append("\",\"age\":");
  61.  
    json.append(age);
  62.  
    json.append(",\"addr\":\"");
  63.  
    json.append(addr);
  64.  
    json.append("\"},");
  65.  
    }
  66.  
    // 上面这样拼接,最后一个JSON格式的对象会多一个逗号,所以进行截串
  67.  
    jsonobj = json.substring(0,json.length()-1) "]";*/
  68.  
     
  69.  
    // 创建一个集合
  70.  
    List<Student> studentList = new ArrayList<>();
  71.  
    while (rs.next()) {
  72.  
    String name = rs.getString("name");
  73.  
    int age = rs.getInt("age");
  74.  
    String addr = rs.getString("addr");
  75.  
    // 将以上数据封装成Student对象
  76.  
    Student s = new Student(name, age, addr);
  77.  
    // 将Student对象放到List集合
  78.  
    studentList.add(s);
  79.  
    }
  80.  
    // 将List集合转换成json字符串
  81.  
    jsonobj = JSON.toJSONString(studentList);
  82.  
     
  83.  
    } catch (ClassNotFoundException e) {
  84.  
    e.printStackTrace();
  85.  
    } catch (SQLException e) {
  86.  
    e.printStackTrace();
  87.  
    } finally {
  88.  
    // 释放资源
  89.  
    if (rs != null) {
  90.  
    try {
  91.  
    rs.close();
  92.  
    } catch (SQLException e) {
  93.  
    e.printStackTrace();
  94.  
    }
  95.  
    }
  96.  
    if (ps != null) {
  97.  
    try {
  98.  
    ps.close();
  99.  
    } catch (SQLException e) {
  100.  
    e.printStackTrace();
  101.  
    }
  102.  
    }
  103.  
    if (conn != null) {
  104.  
    try {
  105.  
    conn.close();
  106.  
    } catch (SQLException e) {
  107.  
    e.printStackTrace();
  108.  
    }
  109.  
    }
  110.  
    }
  111.  
    // 响应JSON格式的字符串给前端
  112.  
    out.print(jsonobj);
  113.  
    }
  114.  
    }
学新通

③前端代码不变

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>发送AJAX请求,显示学生列表</title>
  6.  
    </head>
  7.  
    <body>
  8.  
    <script type="text/javascript">
  9.  
    window.onload = function () {
  10.  
    document.getElementById("btn").onclick = function () {
  11.  
    // 1.创建核心对象
  12.  
    var xhr = new XMLHttpRequest();
  13.  
    // 2.注册回调函数
  14.  
    xhr.onreadystatechange = function () {
  15.  
    if (this.readyState == 4) {
  16.  
    if (this.status == 200) {
  17.  
    //document.getElementById("mybody").innerHTML = this.responseText
  18.  
    // 将json格式的字符串转换成json对象
  19.  
    var stuList = JSON.parse(this.responseText)
  20.  
    // 是一个数组,并且数组中有多个学生数据
  21.  
    var html = ""
  22.  
    for (var i = 0; i < stuList.length; i ) {
  23.  
    var stu = stuList[i]
  24.  
    html = "<tr>"
  25.  
    html = "<td>" (i 1) "</td>"
  26.  
    html = "<td>" stu.name "</td>"
  27.  
    html = "<td>" stu.age "</td>"
  28.  
    html = "<td>" stu.addr "</td>"
  29.  
    html = "</tr>"
  30.  
    }
  31.  
    document.getElementById("mybody").innerHTML = html
  32.  
    } else {
  33.  
    alert(this.status)
  34.  
    }
  35.  
    }
  36.  
    }
  37.  
    // 3.开启通道
  38.  
    xhr.open("GET", "/ajax/ajaxrequest5", true)
  39.  
    // 4.发送请求
  40.  
    xhr.send()
  41.  
    }
  42.  
    }
  43.  
    </script>
  44.  
     
  45.  
    <input type="button" value="显示学员列表" id="btn">
  46.  
    <table border="1px" width="50%">
  47.  
    <tr>
  48.  
    <th>序号</th>
  49.  
    <th>姓名</th>
  50.  
    <th>年龄</th>
  51.  
    <th>住址</th>
  52.  
    </tr>
  53.  
    <!--具体的内容需要连接数据库动态获取,为了便于操作,写一个tbody-->
  54.  
    <tbody id="mybody">
  55.  
    <!--具体内容响应在这里-->
  56.  
    </tbody>
  57.  
     
  58.  
    </table>
  59.  
     
  60.  
     
  61.  
    </body>
  62.  
    </html>
学新通

3、基于XML的数据交换(了解)

xml和JSON都是常用的数据交换格式

①XML体积大,解析麻烦;较少用。

②JSON体积小,解析简单;较常用。

(1)对于以下XML文件,进行数据的交换

  1.  
    <students>
  2.  
    <student>
  3.  
    <name>zhangsan</name>
  4.  
    <age>20</age>
  5.  
    </student>
  6.  
    <student>
  7.  
    <name>lisi</name>
  8.  
    <age>22</age>
  9.  
    </student>
  10.  
    </students>

(2)后端代码

注意:如果服务器端响应XML的话,响应的内容类型需要写成xml。不常用我们就不连接数据库了!

response.setContentType("text/xml;charset=UTF-8");
  1.  
    package com.bjpowernode.javaweb.ajax;
  2.  
     
  3.  
    import javax.servlet.ServletException;
  4.  
    import javax.servlet.annotation.WebServlet;
  5.  
    import javax.servlet.http.HttpServlet;
  6.  
    import javax.servlet.http.HttpServletRequest;
  7.  
    import javax.servlet.http.HttpServletResponse;
  8.  
    import java.io.IOException;
  9.  
    import java.io.PrintWriter;
  10.  
     
  11.  
    /**
  12.  
    * @Author:朗朗乾坤
  13.  
    * @Package:com.bjpowernode.javaweb.ajax
  14.  
    * @Project:ajax
  15.  
    * @name:AjaxRequest6Servlet
  16.  
    * @Date:2022/12/7 16:26
  17.  
    */
  18.  
    @WebServlet("/ajaxrequest6")
  19.  
    public class AjaxRequest6Servlet extends HttpServlet {
  20.  
    @Override
  21.  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
  22.  
    throws ServletException, IOException {
  23.  
    // 设置响应的类型是XML
  24.  
    response.setContentType("text/xml;charset=UTF-8");
  25.  
    PrintWriter out = response.getWriter();
  26.  
     
  27.  
    // 进行拼串
  28.  
    StringBuilder xml = new StringBuilder();
  29.  
    xml.append("<students>");
  30.  
    xml.append("<student>");
  31.  
    xml.append("<name>zhangsan</name>");
  32.  
    xml.append("<age>20</age>");
  33.  
    xml.append("</student>");
  34.  
    xml.append("<student>");
  35.  
    xml.append("<name>lisi</name>");
  36.  
    xml.append("<age>22</age>");
  37.  
    xml.append("</student>");
  38.  
    xml.append("</students>");
  39.  
     
  40.  
    // 响应到给前端
  41.  
    out.print(xml);
  42.  
     
  43.  
     
  44.  
    }
  45.  
    }
学新通

(3)前端代码

①使用responseXML方法接收对象,自动封装为文档对象(xmlDoc)

②通过这个对象调用getElementsByTagName("student")方法获取所有<student>的标签,肯定是一个数组;然后遍历数组,拿到每一个<student>的标签

③再调用childNodes方法拿到<student>标签的所有子元素,也是是一个数组,需要再次遍历,拿到每个子元素或者子节点node;然后子节点调用nodeName方法,看是不是name或者age属性,如果是就调用子节点的textContent方法拿到对应的数据,拼串拼进去

④最后把整个拼好的字符串扔到table里面进行输出!

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>使用XML完成数据交换</title>
  6.  
    </head>
  7.  
    <body>
  8.  
    <script type="text/javascript">
  9.  
    window.onload = function(){
  10.  
    document.getElementById("btn").onclick = function(){
  11.  
    // 1.创建XMLHTTPRequest对象
  12.  
    var xhr = new XMLHttpRequest();
  13.  
    // 2.注册回调函数
  14.  
    xhr.onreadystatechange = function () {
  15.  
    if (this.readyState == 4) {
  16.  
    if (this.status == 200) {
  17.  
    // 服务器端响应了一个XML字符串,这里怎么接收呢?
  18.  
    // 使用XMLHTTPRequest对象的responseXML属性,接收返回之后,可以自动封装成document对象(文档对象)
  19.  
    var xmlDoc = this.responseXML
  20.  
    //console.log(xmlDoc)
  21.  
    // 获取所有的<student>元素,返回了多个对象,应该是数组。
  22.  
    var students = xmlDoc.getElementsByTagName("student")
  23.  
    //console.log(students[0].nodeName)
  24.  
    var html = "";
  25.  
    for (var i = 0; i < students.length; i ) {
  26.  
    var student = students[i]
  27.  
    // 获取<student>元素下的所有子元素
  28.  
    html = "<tr>"
  29.  
    html = "<td>" (i 1) "</td>"
  30.  
    var nameOrAge = student.childNodes
  31.  
    for (var j = 0; j < nameOrAge.length; j ) {
  32.  
    var node = nameOrAge[j]
  33.  
    if (node.nodeName == "name" || node.nodeName == "age") {
  34.  
    //console.log("name = " node.textContent)
  35.  
    html = "<td>" node.textContent "</td>"
  36.  
    }
  37.  
    /*if (node.nodeName == "age") {
  38.  
    //console.log("age = " node.textContent)
  39.  
    html = "<td>" node.textContent "</td>"
  40.  
    }*/
  41.  
    }
  42.  
    html = "</tr>"
  43.  
    }
  44.  
    document.getElementById("stutbody").innerHTML = html
  45.  
    }else{
  46.  
    alert(this.status)
  47.  
    }
  48.  
    }
  49.  
    }
  50.  
    // 3.开启通道
  51.  
    xhr.open("GET", "/ajax/ajaxrequest6?t=" new Date().getTime(), true)
  52.  
    // 4.发送请求
  53.  
    xhr.send()
  54.  
    }
  55.  
    }
  56.  
    </script>
  57.  
    <button id="btn">显示学生列表</button>
  58.  
    <table width="500px" border="1px">
  59.  
    <thead>
  60.  
    <tr>
  61.  
    <th>序号</th>
  62.  
    <th>姓名</th>
  63.  
    <th>年龄</th>
  64.  
    </tr>
  65.  
    </thead>
  66.  
    <tbody id="stutbody">
  67.  
     
  68.  
    </tr>
  69.  
    </tbody>
  70.  
    </table>
  71.  
    </body>
  72.  
    </html>
学新通

(4)执行效果如下:点击按钮,展示数据

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgaehhj
系列文章
更多 icon
同类精品
更多 icon
继续加载