使用jquery ajax从xml中检索单个记录

Retrieving single record from xml using jquery ajax

本文关键字:检索 单个 记录 xml jquery ajax 使用      更新时间:2023-09-26

我是新的jquery,我有一个xml文档,我想ajax只显示一个记录(容器),而不是它显示所有其他记录(容器)。目前它显示所有的记录,而不是我希望它显示一个,例如在代码2问题。

XML文件

<?xml version="1.0" encoding="UTF-8"?>
<container>
<record>
<code>1</code>
<question>what is your name</question>
</record>
<record>
<code>2</code>
<question>what is your day</question>
</record>
</container>
Ajax

$.ajax({
    url:'my.xml',
    dataType:'xml',
    success: function(data){

        function question(e)
        {
                $(data).find('container record').each(function()
                {
                var code = $(this).find('code').text();
                if (code == 2)
                {
                    var record = $(this).find('question').text();
                    $('.timeline').append($('<P />',{text:record}));
                }
                else
                {
                    $('.timeline').append($('<P />',''));
                }

                });
        }
        question();
    },
    error: function(){
        $('.timeline').text('Failed to read feed');
    }   
});
HTML

<div class="timeline">
</div>

您可以使用 :eq() 选择器:

$.ajax({
    url:'my.xml',
    dataType:'xml',
    success: function(data){
        function question(no) {
            var $record = $(data).find('record:eq('+no+')');
            if ($record.find('code').text() == '2') {
                $('.timeline').append($('<P />', {text: $record.find('question').text() }))
            } else {
                $('.timeline').append($('<P />',''));
            }
        }
        question(0); //1, 2, 3 and so on
    },
    error: function(){
        $('.timeline').text('Failed to read feed');
    }   
});