3

I have the following simple jquery snippet

        $(document).ready(function () {
        $.ajax({
             url:"myjson.json",
             dataType: 'json',
             success:function(json){
                 $.each(json, function() {
                    alert("test");
                });
             },
             error:function(){
             },
        });
    });

The result can return 1000's of results - i only want the first 20 for example. How would i best do this?

m90
  • 11,434
  • 13
  • 62
  • 112
brother
  • 7,651
  • 9
  • 34
  • 58
  • 1
    The first choice should be: make your server-side handler accept a parameter that lets the client specify how many results should be returned. Do you have control over the server code? – Jon Mar 23 '12 at 09:30
  • I don't think you can do an AJAX request and just receive the first 20 entries (it has to fetch the whole response), can't you do that server-side like `myjson.json?from=0&to=20`? – m90 Mar 23 '12 at 09:31
  • You'd be better off doing it server-side. What is the point of the overhead of returning 1000+ results if you only need the first 20 ones... – Didier Ghys Mar 23 '12 at 09:31
  • Yeah, do that in on the server side. It does not make sense to let the server fetch all items and send them to the client if you are only interested in a handful of them. – Felix Kling Mar 23 '12 at 09:32
  • Yes, my first thought - but i dont have access to the server-side code. So only option is to do it client side i am afraid. Cant i limit the 4.each somehow? – brother Mar 23 '12 at 09:34

2 Answers2

5

The callback for .each() has an argument index which is the index in the original collection. You break out of the iteration by returning false from the callback.

So you would do something like:

$.each(json, function(index) {
    if(index < 20)
      alert("test");
    else
       return false;
});

As others has commented it is better to do this server side, but maybe you have no access to server side code?

Weston
  • 1,845
  • 13
  • 12
3

In case you really want to (or have to) do this client side you can break an $.each loop by returning false at a certain iteration.

See this fiddle for a basic example of how to do this.

In your case that would lead to:

success:function(json){
                 $.each(json, function(index) {
                    alert("test");
                    if (index === 19){return false}
                });
             }

Also see the docs:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

m90
  • 11,434
  • 13
  • 62
  • 112