无法使用jQuery从外部文件加载xml [英] unable to load xml from external file using jQuery

查看:141
本文介绍了无法使用jQuery从外部文件加载xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码加载外部xml但它无法正常工作

I'm trying to load external xml using the following code but it is not working

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

我有 data.xml js 同一文件夹中的文件。

I have both data.xml and js file in same folder.

chrome 中,它返回 404错误

In chrome it returns 404 error.

FF 中,它返回 0 [异常...访问受限制的URI被拒绝代码:1012nsresult:0x805303f4(NS_ERROR_DOM_BAD_URI)

In FF it retuns 0 [Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)".

我不明白为什么会这样?请详细说明这个问题。

I couldn't understand why this happens? Please shed some light on this issue.

更新:我使用 $。get( ) 如下所述,但仍然没有成功。

Updates: I gave a shot using $.get() as mentioned below but still no success.

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

Meanwhile I also gave a try using pure js like below

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 [在此错误时出现错误]

Error in FF: NS_ERROR_DOM_BAD_URI: Access to restricted URI denied [Break On This Error]

xhttp.send();

xhttp.send();


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

Error in chrome: XMLHttpRequest cannot load file:///C:/Users/admin/Desktop/public_html%281%29/public_html/data.xml. Cross origin requests are only supported for HTTP. xml.js:13 Uncaught NetworkError: A network error occurred.

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

Updates: I found this question useful, but is there any way to solve this problem?

推荐答案

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

After a long struggle and with the help of community I figured out the issue.


同源策略限制从
加载的文档或脚本如何与来自其他来源的资源进行交互。

The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin.

意味着系统文件无法做到这一点,所以借助于此答案,我使用WAMPServer来运行我的脚本,它就像一个魅力。

Means this is not possible with the system file, so with the help of this answer, I used WAMPServer to run my script and it worked like a charm.

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

谢谢!

这篇关于无法使用jQuery从外部文件加载xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆