Ajax请求XML内容
首先导入jar包 采用dom解析xml
首先创建CreatXmlServlet使用Java代码生成xml内容 对请求进行响应
CreatXmlServlet.Java文件代码如下
package com.qf.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import jdk.nashorn.internal.ir.Flags;
public class CreatXmlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CreatXmlServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 查看不同类型的ContentType
// 去路径 D:\apache-tomcat-8.5.11(自己的Tomcat的安装路径)\conf\web.xml中
response.setContentType("application/xml;charset = utf-8");
/*-------使用文档能帮助类获取文档对象--------------*/
Document document = DocumentHelper.createDocument();
// XML只有一个根目录 root
Element root = document.addElement("root");
// 给根节点添加孩子节点
Element book = root.addElement("book");
book.addAttribute("id", "1001");
book.addText("水浒传");
Element element = book.addElement("number");
element.addAttribute("no", "001");
element.addText("编号");
Element pen = root.addElement("pen");
pen.addAttribute("price", "20");
pen.setText("晨光文具");
response.getWriter().write(document.asXML());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
创建jsp界面使用Ajax对xml内容进行请求
TestXml.jsp的代码
pageEncoding="UTF-8"%>
Insert title herewindow.onload = function() {
var xhr = getXMLHttpRequest();
xhr.open("get", "CreatXmlServlet");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var s = xhr.responseXML;
var s1 = s.getElementById("1001");
var content = document.getElementById("content");
alert(s1.innerHTML);
}
}
}
}
测试请求结果
Ajax请求XML文件
1.首先导入jar包
然后创建xml文件用于提供给请求
以c3p0-config.xml文件为例
c3p0-config.xml
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/1713_shop
root
123
30000
30
10
30
100
10
200
创建jsp文件对xm文件使用Ajax方式进行请求
pageEncoding="UTF-8"%>
window.onload = function() {
var xhr = getXMLHttpRequest();
//以get的方式请求xml文件
xhr.open("get", "xml/c3p0-config.xml");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseXML;
var nodelist = result.getElementsByTagName("property");
alert(nodelist.length);
var content = document.getElementById("content");
var s = "";
for (var i = 0; i < nodelist.length; i++) {
var item = nodelist[i];
/*--将结果响应到界面上---*/
s += item.textContent + "
";
}
content.innerHTML = s;
}
}
}
}
Insert title here4.测试结果