【发布时间】:2025-11-27 00:25:02
【问题描述】:
我正在尝试从 servlet 获取 XML 响应。 servlet 返回“application/xml”的内容类型。使用 XmlHttpRequest,我可以得到 responseText,但不能得到 responseXml。我想知道这是否与内容类型或请求类型有关(我正在执行 GET)...?
非常感谢!
我已经削减了所有文件。我认为我设置正确。这是我所拥有的:
------- HTML ------
<html>
<head>
<title></title>
<script src="js/jboard_simple.js" type="text/javascript"> </script>
</head>
<body>
<div id="myDiv">
<h2>No results yet....</h2>
</div>
<form name="searchForm" id="searchForm_id">
<input type="text" name="searchString" id="searchString_id" />
<button type="button" onclick="loadXMLDoc()">Perform Search</button>
</form>
</body>
</html>
------- JavaScript -----------
function loadXMLDoc() {
document.getElementById("myDiv").innerHTML = "searching...";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Do something here...
alert(xmlhttp.responseText);
alert(xmlhttp.responseXml);
processSearchServletResponse(xmlhttp.responseText);
}
}
// Find teh search string
var searchString_el = window.document.getElementById('searchString_id');
var searchString = searchString_el.value;
alert('searchString: ' + searchString);
var searchUrl = "/SimpleServlet?searchString=" + searchString;
xmlhttp.open("GET", searchUrl, true);
xmlhttp.send();
}
function processSearchServletResponse(xmlTxt) {
document.getElementById("myDiv").innerHTML = xmlTxt;
}
------- Servlet --------
import java.io.BufferedOutputStream;
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.apache.log4j.Logger;
import org.apache.log4j.LogManager;
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = LogManager.getRootLogger();
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
BufferedOutputStream bs = null;
String simpleResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>hi</root>";
try {
res.setContentType("text/xml");
res.setCharacterEncoding("UTF-8");
bs = new BufferedOutputStream(res.getOutputStream());
bs.write(simpleResponse.getBytes());
} catch (Exception ex) {
logger.error("JboardSearchServlet.service(): error = ", ex);
} finally {
bs.flush();
bs.close();
}
}
}
【问题讨论】:
-
responseXml可能很挑剔。尝试outlined here 的步骤,然后报告。更糟糕的是,您可能需要parseresponseTextmanually。 -
谢谢!我尝试将编码设置为 UTF-8,并将内容类型设置为 application/xml 和 text/xml,但似乎在所有组合中,responseXml 始终未定义。我也会尝试手动解析 responseText。
标签: javascript xml ajax http get