0

I want to limit the amount of results that are being returned from this AJAX call to 5. I think I could use .slice() to do this but I'm not exactly sure what way to go about it.

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "myurl",
    dataType: "xml",
    cache: false,
    success: parsePopular
  });
});

function parsePopular(popular) {
  $(popular).find("item").each(function() {
    $("#popularArticles").append("<h1><p class='Bold'><a href='" + $(this).find("link").text() + "'>" + $(this).find("title").text() + "</a></p></h1>");
  });
}

Any ideas would be great.

Thanks.

3
  • 4
    It is a really good idea to do this server-side. When you come to a library, you don't say "please, bring me all 977413 books. Oh, thanks, I need these 5". You say "could you, please, bring me these 5 books". It is a really important performance issue. Commented Dec 11, 2015 at 5:58
  • yes @YeldarKurmangaliyev is right, when you dont need some data, then try not sending it across network as it creates lot of issues when you start checking for performance of your pages. "Prevention is better than Cure" Commented Dec 11, 2015 at 6:15
  • Both fair points, noted and will try to do that in the future. Thanks guys.
    – Strobe_
    Commented Dec 11, 2015 at 6:23

2 Answers 2

2

$(popular).find("item").slice(0, 5)

$("div").slice(0, 5).remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>

1

Slice and remove

$(popular).find('item').slice(5).remove();
4
  • .slice(5) will return all item having index beginning at 5 $(popular).find('item').slice(0, 5).remove();` Commented Dec 11, 2015 at 6:07
  • @guest271314 this will remove first 5 elements rather than after first 5 elements. Commented Dec 11, 2015 at 6:09
  • @guest271314 yes, it will return all elements after 5 and then remove them. Which is why your answer is right (hence upvoted) and comment is wrong since you are slicing first 5 and removing those. Commented Dec 11, 2015 at 6:12
  • This only worked for me whenever I entered -5 for whatever reason.
    – Strobe_
    Commented Dec 11, 2015 at 6:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.