How to limit / specify json response when using jQuery.ajax

So, I just recently started using ajax with jQuery. I am wondering if it is possible to limit or indicate what you want from an answer.

So say that I had the following, and I just wanted to get the first 3 people or the last 3 out of 100 people.

$.ajax({ type: "GET", url: "/people" dataType: "json", success: function(data) { // Do some awesome stuff. } }); 

Now I know that you can pas and an additional data object. Can this data object be used to limit or specify the answer I want?

Thanks for any help!

+6
source share
5 answers

You must do a server side filter. Pass the value of the data parameter.

 $.ajax({ type: "GET", url: "/people", data: {limit: 3, order: 'desc'}, dataType: "json", success: function(data) { // Do some awesome stuff. } }); 

Then, on the server side, return a response based on limit and order .

+9
source

Yes, you must use the "data" argument to pass the parameter back to your server, specifying which records you want to return. I usually do this paginated to get lines 1-10 or 21-30. This requires that your server logic understand that the correct amount of data must be returned from the parameter values. If you did not have control over this (the server always sent you 100 records), then in your success handler you will manually pull out 3 records that you wanted.

 $.ajax({ type: "GET", url: "/people" dataType: "json", data: { minRow: 1, maxRow: 10 }, success: function(data) { // Do some awesome stuff. } }); 
+3
source

you will have to limit the result on the server side depending on your type of response. If the answer is in JSON, you can do a for loop to stop it on the 3rd result. I would do mannaly for the server side, as I will reduce the size of the response.

+2
source

If you decide to do this on the client side:

The first argument to the success callback is the data returned from the server.

Since the type of data you expect from the server is JSON, a JavaScript object will be returned. You will get access to the first or last 3 people, as usual, in JavaScript.

For example, if the response from the server is as follows:

 { "people" : [ { name: "Foo" }, { name: "Bar" }, { name: "Baz" }, // and so on... ] } 

You can access the first or last 3 people:

 $.ajax({ type: "GET", url: "/people" dataType: "json", success: function(data) { // Assuming there are 100 people in the "people" array // The first three people console.log( data.people[0] ); // "Foo" console.log( data.people[1] ); // "Bar" console.log( data.people[2] ); // "Baz" } }); 
+2
source

If I understand perfectly .....

I usually send data to an ajax request. In your case, I would send this:

  url:'addres' data: 'from='+value_from+'&to='+to; type:'post' 

On the server side, you can get from and to or something like this (amount, if you want, or another option), and an answer with the results you want

+1
source

Source: https://habr.com/ru/post/928164/


All Articles