注意:如果服务器端响应XML的话,响应的内容类型需要写成:
response.setContentType("text/xml;charset=UTF-8");
xml和JSON都是常用的数据交换格式
基于XML的数据交换,前端代码
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用XML完成数据交换title>
head>
<body>
<script type="text/javascript">
window.onload = function(){
document.getElementById("btn").onclick = function(){
// 1.创建XMLHTTPRequest对象
var xhr = new XMLHttpRequest();
// 2.注册回调函数
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
// 服务器端响应了一个XML字符串,这里怎么接收呢?
// 使用XMLHTTPRequest对象的responseXML属性,接收返回之后,可以自动封装成document对象(文档对象)
var xmlDoc = this.responseXML
//console.log(xmlDoc)
// 获取所有的元素,返回了多个对象,应该是数组。
var students = xmlDoc.getElementsByTagName("student")
//console.log(students[0].nodeName)
var html = "";
for (var i = 0; i < students.length; i++) {
var student = students[i]
// 获取元素下的所有子元素
html += ""
html += ""+(i+1)+" "
var nameOrAge = student.childNodes
for (var j = 0; j < nameOrAge.length; j++) {
var node = nameOrAge[j]
if (node.nodeName == "name") {
//console.log("name = " + node.textContent)
html += ""+node.textContent+" "
}
if (node.nodeName == "age") {
//console.log("age = " + node.textContent)
html += ""+node.textContent+" "
}
}
html += " "
}
document.getElementById("stutbody").innerHTML = html
}else{
alert(this.status)
}
}
}
// 3.开启通道
xhr.open("GET", "/ajax/ajaxrequest6?t=" + new Date().getTime(), true)
// 4.发送请求
xhr.send()
}
}
script>
<button id="btn">显示学生列表button>
<table width="500px" border="1px">
<thead>
<tr>
<th>序号th>
<th>姓名th>
<th>年龄th>
tr>
thead>
<tbody id="stutbody">
tbody>
table>
body>
html>
基于XML的数据交换,后端java程序:
package com.bjpowernode.ajax.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @program: 代码
* @ClassName: AjaxRequest6Servlet
* @version: 1.0
* @description: 服务器端返回XML字符串
* @author: bjpowernode
* @create: 2022-05-15 11:48
**/
@WebServlet("/ajaxrequest6")
public class AjaxRequest6Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 注意:响应的内容类型是XML。
response.setContentType("text/xml;charset=UTF-8");
PrintWriter out = response.getWriter();
/*
zhangsan
20
lisi
22
*/
StringBuilder xml = new StringBuilder();
xml.append("" );
xml.append("" );
xml.append("zhangsan ");
xml.append("20 ");
xml.append("");
xml.append("" );
xml.append("lisi ");
xml.append("22 ");
xml.append("");
xml.append("");
out.print(xml);
}
}