无法使用 jQuery 从外部文件加载 xml

IT技术 javascript jquery xml
2021-03-11 10:17:19

我正在尝试使用以下代码加载外部 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 的访问被拒绝 [中断此错误]

xhttp.send();

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

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

2个回答

也许这就是你正在寻找的......

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

更新

阅读这篇文章

不,这行不通。相同的行为,但为了查看我尝试过的错误$.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意味着仍然错误。
2021-04-30 10:17:19
error: 的第三个参数不是 xhr,它是一个字符串。因此,您当然会变得不确定。记录整个。
2021-04-30 10:17:19
我试过了,但它不起作用。我没有收到任何控制台消息。
2021-05-06 10:17:19
@KevinB 我试过整个,error: function (response, status, err){ console.log( err ); }但只有空的日志打印。
2021-05-14 10:17:19
@PraveenJeganathan 以您目前的方式做也行不通吗?这个答案的方式比你目前正在做的要正确得多。您应该使用此答案并添加错误回调,然后 console.log 错误回调中的三个参数。很可能 xml 无效。
2021-05-17 10:17:19

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

同源策略限制从一个源加载的文档或脚本如何与来自另一个源的资源交互。

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

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

谢谢!

看了 5 分钟,马上就看到了,设置 localhost 是处理这些事情的方法^^
2021-04-21 10:17:19