【发布时间】:2014-09-10 10:59:41
【问题描述】:
我想将表格添加到 html 页面 其数据来自通过 AJAX 以 xml 格式的服务器。我想用 XML 转换来做到这一点。在服务器端,转换工作并按需要显示表,但在客户端,我总是遇到整个 XML 文档而不是转换后的表。实际上,下面的 XMLHttpRequest.responseXML 包含完整的 XML 文档。我将不胜感激。
摘自javascript代码(接收ajax响应的回调函数):
[...]
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
output = xmlhttp.responseXML;
document.getElementById("result").innerHTML = output;
}
[...]
在服务器端,只是为了测试,我设置了一个 JSP 页面,内容如下(如果我启动 JSP 页面,显示表格):
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<?xml-stylesheet type="text/xsl" href="generateXMLXSL.xsl" ?>
<bookstore>
<book publisher="Kiskapu" year="2004">
<author>John Doe</author>
<title>C++ Programozas</title>
<review>Nem tul jo.</review>
</book>
<book publisher="Manning" year="2009">
<author>D. Malavia</author>
<title>SCWD Exam Study Kit</title>
<review>Excellent reading for the exam.</review>
</book>
<book publisher="Manning" year="2013">
<author>Andrew Doe</author>
<title>Web Application Development</title>
<review>Medium</review>
</book>
<book publisher="Sage" year="2008">
<author>Salkind</author>
<title>Exploring Research</title>
<review>Excellent, easy-to-read and interesting!</review>
</book>
</bookstore>
在服务器端工作的简单 xsl 文件:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<table cellspacing="1">
<tr style="background-color: #cccccc">
<th>Author</th>
<th>Title</th>
<th>Review</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr style="background-color: #dedede">
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="review"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
解决方案: Martin 提请我注意,在客户端,如果 xml 来自 XMLHttpRequest 对象,则不会处理 xsl 文件。这回答了我遇到的错误。如何根据变量从javascript转换xml的解决方案可以在这里找到:
【问题讨论】:
-
如果您使用 XMLHttpRequest 加载 XML 文档,则浏览器不会应用 XSLT 样式表。如果您想应用 XSLT 转换,请将 XML 加载到 iframe 或对象中,或者使用脚本在您的代码中自行应用 XSLT。
-
非常感谢,马丁。那将解决问题。您能否也发布一个小样本,您将如何做到这一点?
-
对于 Mozilla、Chrome、Opera、Safari,请参阅 developer.mozilla.org/en-US/docs/…。
-
根据您的第一条评论,我还发现了 2 个可以解决问题的类似查询。我会将它们添加到原始问题中。再次感谢您的回复。
标签: javascript ajax xml xslt