从数据库和编码到字符串的 View
String xml = XMLUtils.marshallToString(list);
sre.getServletRequest().setAttribute("LIST", xml);
和JS代码
var regObject = '${requestScope.LIST}';
...... 当在浏览器中打开时。查看源代码,我遇到错误“意外的 token 非法”。
var regObject = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>//Unexpected token ILLEGAL
<items>
<item>
<id>ID</id>
<productName>PrdName</productName>
<productLink>LINK</productLink>
<productImage>IMG</productImage>
</item>
</items>';
JAXBContext jaxb = JAXBContext.newInstance(List.class);
Marshaller mar = jaxb.createMarshaller();
mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
StringWriter sw = new StringWriter();
mar.marshal(items, sw);
return sw.toString();
有人知道如何解决这个问题吗?
最佳答案
JavaScript 的 '
和 "
字符串文字中不能包含未转义的换行符,因此会出现错误。(ES2015 的反引号模板字符串可以。)
输出 XML 时,您需要确保 JavaScript 字符串文字中可能存在的任何特殊字符,例如 '
(因为您使用的是单引号)、换行符和反斜杠,转义,前面有一个反斜杠。
例如,您希望输出如下所示:
var regObject = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\
<items>\
<item>\
<id>ID</id>\
<productName>PrdName</productName>\
<productLink>LINK</productLink>\
<productImage>IMG</productImage>\
<something>I\'m an example with an apostrophe</productImage>\
<something>I\'m an example with a \\ (backslash)</productImage>\
</item>\
</items>';
或者当然,用 \n
替换换行符(在转义任何现有反斜杠之后):
var regObject = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<items>\n<item>\n<id>ID</id>\n<productName>PrdName</productName>\n<productLink>LINK</productLink>\n<productImage>IMG</productImage>\n<something>I\'m an example with an apostrophe</productImage>\n<something>I\'m an example with a \\ (backslash)</productImage>\n</item>\n</items>';
关于javascript - 加载 xml 对象时出现意外标记非法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33982461/