【发布时间】:2018-07-09 02:28:49
【问题描述】:
我已多次尝试从外部服务器加载XML,但均未成功。
第一个示例在我的服务器上有XML document 时完美地加载了XML,但当我尝试从外部服务器加载相同的XML 时却没有。
第二个示例正在从外部服务器上加载XML,但在我的页面上加载的数据与 XML 不同。
我的XMLHttpRequest 中是否遗漏了什么,或者这是Cross Origin 的问题?
编辑:第二个示例通过将responseText 更改为responseXML 解决,但是第一个示例已经有responseXML,但它不起作用。为什么第一个示例的功能与第二个示例不同?
第一个例子
var n = document.getElementById("search");
n.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET","https://www.w3schools.com/xml/books.xml", true);
xhttp.send();
}
function myFunction(xhttp) {
var a = n.value;
var xmlDoc = xhttp.responseXML;
const { value } = search;
const foundState = [...xmlDoc.querySelectorAll('title')].find(possibleMatch => possibleMatch.textContent === value);
const unit = foundState.parentElement;
console.log(unit.innerHTML);
document.getElementById("titleNode").innerHTML = unit.children[0].textContent;
document.getElementById("authorNode").innerHTML = unit.children[1].textContent;
document.getElementById("yearNode").innerHTML = unit.children[2].textContent;
}
<input type="text" name="search" id="search" placeholder="type 'r'" list="searchresults" autocomplete="off" />
<datalist id="searchresults">
<option value="Everyday Italian">001</option>
<option value="XQuery Kick Start">010</option>
<option value="Learning XML">110</option>
<option value="Harry Potter">101</option>
</datalist>
<button id="myButton" type="button"
onclick="loadDoc('https://www.w3schools.com/xml/books.xml', myFunction)">Submit
</button>
<p>Title node: <span id="titleNode"></span></p>
<p>Author node: <span id="authorNode"></span></p>
<p>Year node: <span id="yearNode"></span></p>
第二个例子
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", "https://data.cityofnewyork.us/api/views/kku6-nxdu/rows.xml", true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML =
xhttp.responseXML;
}
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button"
onclick="loadDoc('ajax_info.txt', myFunction)">Change Content
</button>
</div>
【问题讨论】:
-
如果你的响应是 XML,不要使用
responseText,使用responseXML。而且,在调试 AJAX 调用时,请始终打开开发人员工具的 Network 选项卡,因为它会准确显示正在发生的事情。另外,请注意CORS,默认情况下会阻止跨域请求。 -
谢谢,第一个示例已经使用了 responseXML,但不起作用。我更新了第二个示例以也使用 responseXML,并且该示例现在似乎可以工作。我没听懂。
-
您的第一个示例在
onreadystatechange上调用cFunction(this);,但您没有声明该函数。你确实有myFunction,但它永远不会被调用。
标签: javascript ajax xml xmlhttprequest