我是 javascript 和 REST 服务的新手。我正在尝试从 url 获取一些数据。我写的javascript代码如下:-
<script>
var request = new XMLHttpRequest();
request.open("GET", "https://findtest.akamai.com/_api/search/query?querytext=%27Agora%27&sourceid=%2782cdf98b-cc8b-48c3-a706-d88c1333cc4b%27&QueryTemplatePropertiesUrl=%27spfile://webroot/queryparametertemplate.xml%27&rowlimit=60&selectproperties=%27Title,Author,Url,Date%27&StartRow=%270%27&trimduplicates=%27true%27", false);
request.send();
var xml = request.responseText;
document.write(xml);
</script>
当我在浏览器 IE/Chrome 中打开它时:- 同样的响应在屏幕上闪烁一会儿,然后显示正确的 XML,如下所示:-
我无法在 JavaScript 中获取响应 XML。我必须解码某种编码吗?我想要正确的 XML 响应。
最佳答案
请记住,在写入 HTML 页面时,您编写的是 HTML,而不是纯文本。 <
和&
(至少)必须被编码为实体。
document.write
在 2018 年(或者说在 21 世纪)几乎没有任何地位。您可以改为附加一个文本节点,以便将字符串用作文本,而不是 HTML:
document.body.appendChild(document.createTextNode(xml));
示例:
var xml = "<root><thing/><another-thing/></root>";
document.body.appendChild(document.createTextNode(xml));
您甚至可以将其包装在 code
中元素:
var code = document.createElement("code");
code.appendChild(document.createTextNode(xml));
document.body.appendChild(code);
示例:
var xml = "<root><thing/><another-thing/></root>";
var code = document.createElement("code");
code.appendChild(document.createTextNode(xml));
document.body.appendChild(code);
关于javascript - javascript 中收到的响应不是 XML,而在浏览器上它显示的是 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48057158/