简体   繁体   English

在AJAX中检索XML响应

[英]Retrieving XML response in AJAX

I've written a java code (Spring controller) snippet to send XML response to an AJAX. 我已经编写了一个Java代码(Spring控制器)代码段,以将XML响应发送到AJAX。 Unfortunately I'm unable to get the response as XML using xhr.responseXML but can as a text using xhr.responseText . 不幸的是,我无法获得响应,XML使用xhr.responseXML ,但可以作为文本使用xhr.responseText Instead of parsing the text at client side would someone suggest what was the actual issue? 有人会建议实际问题是什么,而不是在客户端解析文本? Here I am enclosing controller and AJAX code. 在这里,我附上控制器和AJAX代码。

Spring controller code:
-------------------------------
String xmlResp = "<cities>";
xmlResp+="<city>";
xmlResp+="<name>" + "Hyderabad" + "</name>";
xmlResp+="<population>" + "3000000" + "</population>";
xmlResp+="</city>";
xmlResp+="<city>";
xmlResp+="<name>" + "Bangalore" + "</name>";
xmlResp+="<population>" + "4500000" + "</population>";
xmlResp+="</city>";
xmlResp+="</cities>";

response.setContentType("text/xml");
response.getWriter().write(xmlResp);


AJAX code:
-----------------------------

reading as XML:

var xml=xhr.responseXML;
        alert(xml);

reading as Text
var text=xhr.responseText;
        alert(text);

for convenience the XML structure: 为了方便起见,XML结构:

<cities>
    <city>
        <name>Hyderabad</name>
        <population>3000000</population>
    </city>
    <city>
        <name>Bangalore</name>
        <population>4500000</population>
    </city>
</cities>

Your XML is not well-formed: 您的XML格式不正确:

String xmlResp = "'<'cities>";

will give: 会给:

'<'cities>
  • Do use a validator or lint to check your XML 使用验证器或棉绒检查您的XML
  • Don't build an XML document by mashing strings together, use an XML library instead 不要通过将字符串混在一起来构建XML文档,而应使用XML库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM