【问题标题】:How to check if XML string contains certain value in jQuery如何检查XML字符串是否包含jQuery中的某些值
【发布时间】:2014-08-24 07:17:51
【问题描述】:

我想使用 Ajax 来检查 XML 字符串(“data”)是否在“voteBy”下包含某个值,例如名称“John Doe”。如果是,那么我想显示一个警报,如果不是,那么显示另一个警报。背后的想法是我想稍后在这里使用 jQuery 做一些事情,但前提是在 XML 字符串中找不到搜索词。

我尝试了以下是获取此 XML 字符串的 Ajax 调用的成功函数。在这种情况下,当搜索词出现在 XML 字符串中时,它应该提醒“找到”,但我的方法不返回任何内容。

谁能告诉我我在这里做错了什么?注意:XML 的数据可能会有所不同,因此对某个项目的投票可能或多或少,也可能没有。

我的 XML 如下所示(示例数据,已缩短):

<ranks>
  <itemDetails>
    <itemID>1</itemID>
    <title>Test item</title>
    <details>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit...&lt;/p&gt;</details>
    <lastUpdate>Added</lastUpdate>
    <modTime>Saturday, 23 August 2014</modTime>
    <modBy>Someone</modBy>
    <comments>
      <commentID>1</commentID>
      <comment>Some comment</comment>
    </comments>
    <comments>
      <commentID>2</commentID>
      <comment>Another comment</comment>
    </comments>
    <votes>
      <voteBy>John Doe</voteBy>
    </votes>
    <votes>
      <voteBy>Jane Doe</voteBy>
    </votes>
  </itemDetails>
</ranks>

我的 jQuery(仅限成功函数,已缩短)- 这里的数据是我的 XML 字符串:

$.ajax({
    // ...
    success:function(data) {    
        if(!$(data).find('voteBy').text() == 'John Doe') {
            alert('not found');
        } else {
            alert('found');
        }
    }
});

【问题讨论】:

    标签: jquery ajax xml find


    【解决方案1】:

    一种方法是为 xml 节点使用.each 元素:

    var yourXML;     
    function search_xml(string_for_search){
      $.ajax({
         type:"GET",
         url: "xml_file.xml",
         dataType: "xml",
         success: function(xml){
    
              $(xml).find('voteBy').each(function(){
              if($(this).text() == string_for_search) alert ('found :)');
              else alert ('not found ! :(');
              });
    
            }
      });
    }
    
    search_xml("John Does");
    

    另一种方式:使用.filter.find

    var yourXML;     
    function search_xml(string_for_search){
      $.ajax({
         type:"GET",
         url: "xml_file.xml",
         dataType: "xml",
         success: function(xml){
                  // Filter 
                myXML = $(xml).find("itemDetails").filter(function() {
                    return $(this).find('voteBy').text() == string_for_search;
                });
    
                 // Store a string with your keywords 
                var output = myXML.children().map(function() {
                    return this.tagName + '=' + $(this).text();
                }).get().join(' ');
    
                alert(output);
            }
      });
    }
    
    search_xml("John Doe");
    

    【讨论】:

    • 非常感谢 - 这看起来不错!除了存储结果之外,还有一种方法可以根据是否找到搜索词来提醒某些东西?
    • @user2571510 如果您的问题解决了,请接受我的回答。
    猜你喜欢
    • 2011-03-31
    • 2016-08-09
    • 2018-05-01
    • 2014-05-07
    • 2019-12-29
    • 2015-03-15
    • 2010-11-22
    • 2015-03-14
    相关资源
    最近更新 更多