weixin_33739523 2016-12-02 19:05 采纳率: 0%
浏览 8

返回一个特定的数据

I would like to specifically return one data from xml.

If nameOfBusiness = Restaurant then it returns all the ratings (the three restaurants) with an itemname that has Restaurant.

How can I make it only alert one Restaurant and not including the other 2 Restaurant(with Steams and Origins)?

Here is my xml:

<resultitem>
 <itemname>Restaurant</itemname>
 <rating>3</rating>
</resultitem>
<resultitem>
 <itemname>Restaurant Origins</itemname>
 <rating>4</rating>
</resultitem>
<resultitem>
 <itemname>Restaurant Steams</itemname>
 <rating>4.1</rating>
</resultitem>

Here is my ajax code:

$.ajax({
  type: 'GET',
  url: 'someURL.xml',
  dataType: 'xml',
  success: function(xml) {
    var found = $(xml).find('resultitem itemname:contains("' + nameOfBusiness + '")');
    if (!found.length) {
      alert("Rating not published yet");
      return;
    }
    found.each(function() {
      var rating = $(this).parent().find('rating').text();
      alert("The rating for " + nameOfBusiness + " is " + rating);
    })
  }
});
  • 写回答

1条回答 默认 最新

  • 七度&光 2016-12-02 19:44
    关注

    For just the first item, you can use:

    const foundRating = found.first().parent().find('rating').text();
    

    You can also break out of the loop by returning false:

    found.each(function(i, v) {
        if (i === 0) {
            var rating = $(this).parent().find('rating').text();
            alert("The rating for " + nameOfBusiness + " is " + rating);
            return false;
        }
    });
    

    jQuery each docs

    评论

报告相同问题?