[英]pass xml from jsp to javascript
So I have a JSP file which gets an xml file from the session: 所以我有一个JSP文件,它从会话中获取一个xml文件:
<%
org.w3c.dom.Document list = (org.w3c.dom.Document) session.getAttribute("list");
%>
<script type="text/javascript">
var list = <%=list %>
</script>
And I want to use it in javascript but I can't seem to find a way to load an XML file without providing an URL. 我想在javascript中使用它,但似乎找不到不提供URL即可加载XML文件的方法。 The XML file is stored in a database so providing an URL is not possible.
XML文件存储在数据库中,因此无法提供URL。 Does anyone know how to do this?
有谁知道如何做到这一点?
It would be a two step process, first you need to pass the xml from java to javascript as string, like below 这将是一个两步过程,首先您需要将XML从Java作为字符串传递给javascript,如下所示
var xmlString = "<%=session.getAttribute('list')%>"
and then parse the xml string to XMLDocument. 然后将xml字符串解析为XMLDocument。 Example using jQuery -
使用jQuery的示例-
var xml_doc = jQuery.parseXML(xmlString);
For reference : 1. jQuery.parseXML() 供参考:1. jQuery.parseXML()
First transform your xml Document
Object to String 首先将您的xml
Document
对象转换为字符串
<%@ page import="javax.xml.transform.*" %>
<%
org.w3c.dom.Document list = (org.w3c.dom.Document) session.getAttribute("list");
String xmlAsString = "";
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(list), new StreamResult(sw));
xmlAsString = sw.toString();
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}
%>
Then you can use pass it to a javascript variable (don't forget the quotes): 然后,您可以将其传递给javascript变量(不要忘记引号):
<script type="text/javascript">
var list = '<%=list %>';
</script>
Maybe it's also good for you to escape some characters: 也许转义一些字符对您也有好处:
var list = '<%=list.replaceAll("'","\\'") %>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.