简体   繁体   English

为什么在使用文件时在jQuery中无法进行xml解析?

[英]Why xml parsing doesn't work in JQuery when working with file?

I want to parse an xml file that exists same directory with the html file running. 我想解析与html文件运行相同目录的xml文件。 But it doesn't give any response when I used "data.xml". 但是当我使用“ data.xml”时,它没有给出任何响应。 How can I fix that? 我该如何解决?

My XML file: 我的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<Infos>
<Info name="Stephen" mail="example@gmail.com"/>
</Infos>

My code: 我的代码:

<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
    $(document).ready(function () {
        $(".button").click(function () {
            var xml = "/data.xml"; //How to set path this line?
            xmlDoc = $.parseXML(xml);
            $xml = $(xmlDoc);
            $title = $xml.find("Info");

            alert($title.text());
        });
    });
</script>

var xml = "/data.xml"; creates String "/data.xml" , does not request file at location /data.xml at filesystem 创建String "/data.xml" ,不请求文件系统上位置/data.xml的文件

Note also, no .textContent appear defined for Info element alert( $title.text() ); 还要注意,没有为Info元素alert( $title.text() );定义任何.textContent alert( $title.text() ); would alert empty string. 会提醒空字符串。

Try using $.ajax() to request file from filesystem ; 尝试使用$.ajax()从文件系统请求文件; removing $.parseXML() wrapping response in jQuery() 删除jQuery() $.parseXML()包装响应

$(document).ready(function () {
    $(".button").on('click', function () {
        var xml = "/data.xml"; //How to set path this line?

        $.ajax({
            url : xml, 
            dataType : "xml"
        }).done(function(xmlDoc) {

            var $title = $(xmlDoc).find("Info");
            // alert( $title.text() );

        }).fail(function(jqxhr, textStatus, errorThrown) {
             console.log(errorThrown)
        });
    });
});

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

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