【问题标题】:jquery read child xml datajquery读取子xml数据
【发布时间】:2013-02-07 12:12:52
【问题描述】:

我想知道如何修复我的脚本,我希望在您单击按钮时发出警报,但它会跟上同一页面上 xml 发生的变化。 当然,当我单击按钮时,我认为这个脚本会起作用,但什么也没有发生。我想看看我是否可以从更有经验的人那里获得任何意见。

$(document).ready(function(){

function get_info() {
    $.ajax({
        type: "GET",
        url: "xmldata/product.xml",
        dataType: "xml",
        cache: false,
        complete: function(doc) {
            var product = $(doc.responseText).find("product").text() == 1;
            var name = product.next().children("name").text();
            var cost = product.next().children("cost").text();
            $("#xmlalert").click(function(){
                                alert(cost);
            })
        }
    });

}
setInterval(function() {
    get_info();
}, 5000);
});

xml数据如图:

<?xml version="1.0" encoding="utf-8"?>
<store>
   <product>1</product>
    <info>
        <name>Toy</name>
        <cost>1196</cost>
    </info>
</store>

【问题讨论】:

    标签: xml ajax jquery xml-parsing


    【解决方案1】:

    HTML代码

    <button class="button" id="1">One</button>
    <button class="button" id="2">Two</button>
    

    更改您的 javascript 代码,例如:

    $(document).ready(function(){
          function get_info() {
            $.ajax({
                type: "GET",
                url: "xmldata/product.xml",
                dataType: "xml",
                cache: false,
                complete: function(doc) {
                $(".button").click(function(event){
                    console.log($(this).attr('id'));
                    var product = $(doc.responseText).find("product").eq($(this).attr('id')-1);
                    var currentIndex=0;
                    product.each(function(index){
                        var name = $(this).next().children("name").text();
                        var cost = $(this).next().children("cost").text();
                        alert(cost);    
                    });
                });
            }
            });
    
            }
            setInterval(function() {
                get_info();
            }, 2000);
    });
    

    XML 是

    <?xml version="1.0" encoding="utf-8"?>
    <store>
       <product>1</product>
        <info>
            <name>Toy</name>
            <cost>1196</cost>
        </info>
        <product>2</product>
        <info>
            <name>Toy 2</name>
            <cost>11962</cost>
        </info>
    
    </store>
    

    【讨论】:

    • 我不想问太多,但是xml文件叫什么和是否在子文件夹里有区别吗?例如,您的 cml.xml 也是通过使用 find("product") 只能找到一个?有没有更具体的方法?因为此 xml 将包含多个产品,例如产品 1、产品 2 等。
    • 好的,我为此更改了答案。
    • 谢谢,实际上我在查看您的答案之前就知道了这一点,哈哈,但它现在同时提醒两种成本,因为我希望它只提醒一个。一个单独的按钮将用于第二个。
    • 但是如果产品数量多的话会有问题,可以说50-100吗?
    • json 会不会更容易更好?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    相关资源
    最近更新 更多