如何使用jQuery和Ajax解析多个项目?

时间:2013-08-05 14:03:41

标签: jquery xml

我正在尝试使用jQuery Ajax解析XML文件中的多个项目,用于xml结构:

<titles>
    <titleitem>
        <authors>
            <author>1</author>
            <author>2</author>
            <author>3</author>
        </authors>
    </titleitem>
</titles>

其中每个<titleitem>具有不同数量的作者(或者,上面的示例中未显示,也包含不同数量的主题)。

我的确切jQuery和XML如下。我当前代码发生的情况是,每个项目都列出了所有<author>,而不是仅列出了列出的特定<author>的{​​{1}}。如果你能帮助我,我会非常感激。

除上述内容外,我还需要为每个<titleitem>设置一个特定网址,并为每个<author>设置一个特定网址。我在下面的XML中没有这些URL。您能否告诉我如何为每个<topic><author>添加该特定网址?

非常感谢!

XML:

<topic>

jQuery的:

<titles>

  <titleitem id="0">
    <title>This is one title</title>
    <subtitle>This is an example of a subtitle</subtitle>
    <authors>
      <author>Steve Johnson</author>
      <author>Michael Smith</author>
    </authors>
    <topics>
      <topic>Technology</topic>
    </topics>
    <imagelg type="html"><![CDATA[http://www.google.com/serverfiles/productimages/sf113072b.jpg]]></imagelg>
    <url type="html"><![CDATA[http://www.google.com/ProductDetail.aspx?ProductId=123456]]></url>
    <desc>
      <brief type="html"><![CDATA[This is a brief description]]></brief>
      <long type="html"><![CDATA[text here]]></long>
    </desc>
  </titleitem>

  <titleitem id="1">
    <title>This is another title</title>
    <subtitle>This is an example of a subtitle</subtitle>
    <authors>
      <author>John Williams</author>
    </authors>
    <topics>
      <topic>Management</topic>
      <topic>Info</topic>
      <topic>Systems</topic>
    </topics>
    <imagelg type="html"><![CDATA[http://www.google.com/serverfiles/productimages/sf113075b.jpg]]></imagelg>
    <url type="html"><![CDATA[http://www.google.com/ProductDetail.aspx?ProductId=123456]]></url>
    <desc>
      <brief type="html"><![CDATA[This is a brief description]]></brief>
      <long type="html"><![CDATA[text here]]></long>
    </desc>
  </titleitem>
<titles>

2 个答案:

答案 0 :(得分:2)

尝试

$(this).find('author').each(function(){
    var author = $(this).text();
    $('<a href="#"></a>').html(author).appendTo('#link_'+id+' div.itemauthor');
});

因为无论authors标记如何,您都想迭代作者标记。还可以使用当前链接div id将其仅附加到那个。


$(this).find('author').each(function(){
    var name = $(this).find('name').text();
    var link = $(this).find('link').text();
    $('<a href="'+link+'"></a>').html(name).appendTo('#link_'+id+' div.itemauthor');
});

答案 1 :(得分:-1)

我认为你的问题在于代码:

$('<a href="#"></a>').html(author).appendTo('div.itemauthor');

编辑:更改了代码。

尝试将代码更改为:

$(xml).find('titleitem').each(function(){
    ...
    var $self = $(this);
    ...

    $(this).find('authors').each(function(){
        $('<a href="#"></a>').html(author).appendTo('div.itemauthor', $self);
    });

    ...
} 

这只会将作者附加到上下文中。