【问题标题】:unable to load xml from external file using jQuery无法使用 jQuery 从外部文件加载 xml
【发布时间】:2013-11-08 18:22:50
【问题描述】:

我正在尝试使用以下代码加载外部 xml,但它不起作用

$( document ).load( "data.xml", function(  response, status, xhr ) {        
    console.log( xhr.status + " " + xhr.statusText );
  });

我在同一个文件夹中有data.xmljs 文件。

chrome 中返回 404 error

FF 中,它返回 0 [Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)"

我不明白为什么会这样?请对此问题有所了解。

更新:我使用 $.get() 进行了测试,如下所述,但仍然没有成功。

同时我也尝试使用下面的纯js

function loadXMLDoc(dname) {
    if (window.XMLHttpRequest)    {
      xhttp=new XMLHttpRequest();
      }
    else {
      xhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xhttp.open("GET",dname,false);
    xhttp.send();
    return xhttp.responseXML;
}
    xmlDoc=loadXMLDoc("data.xml");
    console.log(xmlDoc);

仍然面临错误。

FF 中的错误: NS_ERROR_DOM_BAD_URI:访问受限 URI 被拒绝 [Break On This Error]

xhttp.send();

chrome 中的错误: XMLHttpRequest 无法加载 file:///C:/Users/admin/Desktop/public_html%281%29/public_html/data.xml。 仅 HTTP 支持跨源请求。 xml.js:13 未捕获 NetworkError:发生网络错误。

更新: 我发现这个question 很有用,但是有什么办法可以解决这个问题吗?

【问题讨论】:

  • $( document ).load( "data.xml" 没有任何意义。
  • 首先,您几乎可以肯定在这里使用.get() 而不是.load()
  • @KevinB 那我需要使用任何元素吗?例如$('#someid').load(..如果我的意思错了请纠正我?
  • @Pointy 我尝试使用.get(),但它没有记录控制台消息。
  • 我希望您使用本地网络服务器进行测试。查看您的控制台错误输出,我看到您正在尝试从 file:// 协议获取文件,而该文件应该是根文件夹的相对路径,然后使用 http:// 协议。

标签: javascript jquery xml


【解决方案1】:

也许这就是你要找的......

$(document).ready(function(){
    $.ajax({
        url: 'data.xml',
        dataType: 'xml',
        success: function(response, status, xhr){
           console.log( xhr.status + " " + xhr.statusText );
        }
     });
});

更新

阅读此post

【讨论】:

  • 我试过了,但它不起作用。我没有收到任何控制台消息。
  • 不,这不起作用。相同的行为,但为了查看错误,我尝试了 $.ajax({ url: 'data.xml', dataType: 'xml', success: function(response, status, xhr){ console.log( xhr.status + " " + xhr.statusText ); }, error: function (response, status, xhr){ console.log( xhr.status + " " + xhr.statusText ); } }); 现在它记录了 undefined undefined 意味着仍然错误。
  • @PraveenJeganathan 以您当前的方式进行操作也行不通吗?这个答案的方式比你目前正在做的要正确得多。您应该使用这个答案并添加一个错误回调,然后 console.log 来自错误回调的三个参数。 xml 很可能是无效的。'
  • error的第三个参数:不是xhr,是字符串。因此,您当然会变得不确定。全部记录下来。
  • @KevinB 我像error: function (response, status, err){ console.log( err ); } 一样尝试了整个过程,但只打印了空日志。
【解决方案2】:

经过长期的斗争并在社区的帮助下,我找到了问题所在。

同源策略限制如何从 一个来源可以与另一个来源的资源交互。

意味着这对于系统文件是不可能的,所以在answer 的帮助下,我使用 WAMPServer 来运行我的脚本,它就像一个魅力。

 $.get("http://localhost/public_html(1)/public_html/xml/data.xml",
                                     function(  response, status, xhr ) {        
        console.log( response );
    });

谢谢!

【讨论】:

  • 看了5分钟,马上就看到了,设置本地主机是处理这类事情的方法^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多