开发者

Loading xml with Jquery - why doesn't this work

开发者 https://www.devze.com 2023-01-01 15:22 出处:网络
I have regular javascript code and am trying to utilize JQuery just to load and parse an xml file.I have the following:

I have regular javascript code and am trying to utilize JQuery just to load and parse an xml file. I have the following:

function loadXml() {
  $(function() {
        $.ajax({
                type: "GET",
 开发者_Go百科               url: "my_file.xml",
                dataType: "xml",
                success: parseXml

        });
    });

}

function parseXml() {
   alert("Parsing...");
}

When calling loadXml I cannot get the callback success function to execute. I am running this all locally and my_file.xml resides in the same directory as this javascript. Any ideas?


Also why are you using the DOMReady shortcut function inside of another function, that doesn't make any sense.

Remove the $(function() { }); That might even fix your problem...

If anything should be set up like this:

jQuery(function($) {
    loadXML()
});

Full code would look like this (with the my_file.xml residing in the exact same directory):

<script src="http://code.jquery.com/jquery.js"></script>
<script>
function loadXml() {
        $.ajax({
                type: "GET",
                url: "my_file.xml",
                dataType: "xml",
                success: parseXml

        });
}

function parseXml(data) {
   alert(data);
}


$(function() {
loadXml();
});
</script>


Most modern browsers will not allow the use of ajax to retrieve file:// based resources, even when the main document is run from the 'same' domain.

So in effect, you are running into the Same Origin Policy here.

Just set up a local http webserver and it should be no problem.

To explain the problem:

What if a document you downloaded into c:\users\foo\documents\CoolApp\ could read ANY file on the 'same' domain?

I guess you get my drift...

0

精彩评论

暂无评论...
验证码 换一张
取 消