简体   繁体   English

无法使用 java 脚本解析 xml DOM(来自文件)

[英]Unable to Parse xml DOM (from file) with java script

I've recently begun running into problems with javascript when I attempt to load element tags from a separate xml file into an html document.当我尝试将元素标签从单独的 xml 文件加载到 html 文档中时,我最近开始遇到 javascript 的问题。 I know that I have enabled either XMLHttpRequest or activeX (depending on the internet browser) correctly, but I'm having problems getting the xml file and opening it to access it's tags.我知道我已正确启用 XMLHttpRequest 或 activeX(取决于 Internet 浏览器),但在获取 xml 文件并打开它以访问它的标签时遇到问题。 In order to open the file, I tried to use:为了打开文件,我尝试使用:

xhttp.open("GET",filepath,false);
xhttp.send();
xmlDoc=xhttp.responseXML;

the code appears to make it past the first line, but it gets tripped up at the second.该代码似乎使它超过了第一行,但它在第二行被绊倒了。 I'm wondering if someone would be able to clarify the function of.send(), and if server permissions may by at fault;我想知道是否有人能够澄清 function of.send(),以及服务器权限是否可能是错误的; IE 7/8 it tells me "access is denied" when this block of code runs.当这段代码运行时,IE 7/8 它告诉我“访问被拒绝”。

Make sure that ajax requests are sent to the same domain from the resources were accessed.确保 ajax 请求从被访问的资源发送到同一个域。

Taking your code sample here,在这里获取您的代码示例,

xhttp.open("GET",filepath,false);
xhttp.send();

You have requested for a resource with HTTP method GET.您已使用 HTTP 方法 GET 请求资源。 This request will be fired only once the send() method is called on the XHR object according to the specification[ 1 ].只有根据规范 [ 1 ] 在 XHR object 上调用 send() 方法后,才会触发此请求。 The arguments for send() will be ignored if the method is GET.如果方法是 GET,则 send() 的 arguments 将被忽略。

Now once the xhr object is created, it goes through different states[ 2 ] such as现在一旦创建了 xhr object,它就会经历不同的状态[ 2 ],例如

  • UNSENT (numeric value 0)未发送(数值 0)
  • OPENED (numeric value 1)已打开(数值 1)
  • HEADERS_RECEIVED (numeric value 2) HEADERS_RECEIVED(数值 2)
  • LOADING (numeric value 3)正在加载(数值 3)
  • DONE (numeric value 4)完成(数值 4)

The moment the request is fired(ie, the send() is called), the xhr object will have a state of OPENED.在请求被触发的那一刻(即调用 send()),xhr object 将有一个 state 的 OPENED。

Now, if we look at the 3rd line of your code "xmlDoc=xhttp.responseXML;", it is quite unclear at what state you are trying to read the content.现在,如果我们查看您的代码“xmlDoc=xhttp.responseXML;”的第 3 行,那么您正在尝试读取内容的 state 非常不清楚。 The best way to read the content is when the state reaches 4 or DONE阅读内容的最佳方式是当 state 达到 4 或 DONE

Just modify your code as given below:只需修改您的代码,如下所示:

 var xhr = new XMLHttpRequest();
    xhr.open("GET", somefilepath, true);
    xhr.send();
    xhr.onreadystatechange = function() {
     if(this.readyState == 4) {
      xmlDoc=xhr.responseXML;
     }
   }

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

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