javascript XMLHttpRequest requestXML 为 null
我正在尝试从 url 获取 xml 文档,然后解析它。我可以在浏览器上很好地打开它,但它似乎无法通过我的 JavaScript 运行。谁能帮助我吗?
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = function(){};
callback(request, request.status);
}
};
request.open('GET', "url", true);
request.send(null);
}
downloadUrl("http://jojo.theone.net/survey.xml", function(data) {
alert("Inside downloadURL"); // shows up
var xml = request.responseXML;
alert(xml); // Doesn't even show up.
alert(request.responseText); // Doesnt show up.
});
I'm trying to grab an xml document from a url and then parse it. I am able to open it fine on a browser, but it doesnt seem to work through my javascript. Can anyone help me?
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = function(){};
callback(request, request.status);
}
};
request.open('GET', "url", true);
request.send(null);
}
downloadUrl("http://jojo.theone.net/survey.xml", function(data) {
alert("Inside downloadURL"); // shows up
var xml = request.responseXML;
alert(xml); // Doesn't even show up.
alert(request.responseText); // Doesnt show up.
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在回调方法中使用
data
作为参数名称,但将回调方法调用为callback(request, request.status)
。结果是 request 对象现在位于名为“data”的 var 中,而 request.status 根本没有被引用。尝试
You are using
data
as the parameter name in your callback method, but calling the callback method ascallback(request, request.status)
. The result is that the request object is now in the var called "data", and the request.status is not referenced at all.Try
尝试使用
data
值而不是request
对象。另外,最好使用 Mootools 或 jQuery 等框架来执行 AJAX 请求——您将获得更兼容和可预测的界面。另请注意,如果您请求的 url 与发出请求的脚本具有不同的服务器、端口和协议,则请求将会失败。
Try to use
data
value not therequest
object. Also it is better to use some framework like Mootools or jQuery to perform AJAX requests -- you'll get a more compatible and predictable interface.Also note that request will fail if the url you're requesting has different server, port and protocol than the script that is making request.