Only return the first 20 results of JSON data passed by $ .ajax?

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 might return 1000 results - I want, for example, only the first 20. How would I best do this?

+3


source to share


2 answers


The callback for .each()

has an argument index

that is the index in the source collection. You exit 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 have commented, it is better to do this server-side, but perhaps you don't have access to the server-side code?

+5


source


If you really want (or should) do this client-side, you can break the loop $.each

by returning false

at a specific iteration.

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

In your case, this would result in:



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

      

Also see docs :

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

+3


source







All Articles