jQuery根据第一个XML读取新的XML

时间:2011-02-03 16:07:48

标签: jquery jquery-ui

我有工作jQuery代码,它在http://fiddle.jshell.net/gaby/UC2dM/2/show/工作并读取XML。

现在我需要做的是当有人点击新闻,文章,目的地(作为示例)时,它应该读取相应的XML及其数据。

例如,News xml将是“data_96.xml”文章会读取“data_97.xml”等等......

data_catid.xml的通用格式如下所示

<record>
    <recordId>251</recordId>
    <title>Czech Sandstone Chalk Ban Lifted</title>
    <author>|</author>
    <published>2010-01-20T14:36:00.000-08:00</published>
    <origUrl>http://www.rockandice.com/news/358-Czech-Sandstone-Chalk-Ban-Lifted</origUrl>
    <numComments>0</numComments>
    <data>&lt;![CDATA[&lt;p&gt;According to a report on czechclimbin</data>
</record>

请让我知道如何更改Jquery代码以阅读xmls ..


这是我的Jquery代码

<script type='text/javascript'>
  //<![CDATA[ 
  $(window).load(function(){

  $.ajax({
    url:'data.xml',
    dataType: 'xml',
    type:'post',
    success: function(data){
        var xml = $(data);
        $('#container').append( CategoryToUl(xml.children()) );

    }
});

function CategoryToUl(xml){
    var categories = xml.children('category');
    if (categories.length > 0)
    {
        var ul = $('<ul/>');
        categories.each(function(){
            var $this = $(this);
            var li = $('<li/>');
            var a = $('<a/>',{
                text: $this.children('title').text(),
                href: '#' + $this.children('catId').text()
            });
            li.append(a);
            li.append( CategoryToUl( $this ) );
            ul.append(li);
        });
        return ul;
    }
    return null;
}

  });
  //]]> 
  </script>

</head>
<body>
  <div id="container"></div>

</body>

2 个答案:

答案 0 :(得分:0)

您只需添加以下内容:

<script type='text/javascript'>
  //<![CDATA[ 
  $(window).load(function(){

$('a').live('click', function() {
    var catId = $(this).attr('href').replace('#', '');    
    //here you can use $.get to get your new xml file. 
    //construct the url using the catid
    //you would then parse the xml to display it.
});

//here is the rest of your code

答案 1 :(得分:0)

您可以在CategoryToUl方法中进行更改,链接生成为

var a = $('<a/>',{
    text: $this.children('title').text(),
    href: '#',
    'data-id': $this.children('catId').text(),
    class='categoryrecord'
});

并在$(window).load(function(){下添加

$('a.categoryrecord').live('click',function(e){
   e.preventDefault();
   var cid = $(this).data('id');
   $.ajax({
      url:'data_' + cid + '.xml',
      dataType: 'xml',
      type:'post',
      success: function(data){
          var xml = $(data);
          // .. do what you want here with the xml
      }
   });
});