Best way to check a GET

1

Good afternoon everyone!

I am trying to implement a GET call with Jquery where I iterate a list and I have it as follows.

<script>
$(document).ready(function(){

    $.getJSON("https://jsonplaceholder.typicode.com/posts", function(result){
        $.each(result, function(i, field){
            console.log("UserId: " + field.userId);
            console.log("Field: " +field.id);
            console.log("Title: " + field.title);
        });
    });


    $.ajax({
        type: 'GET',
        url: 'https://jsonplaceholder.typicode.com/posts',
        dataType: 'json',
        success: function(resp){
            console.log("OK");
            console.log(resp);
        }
    });

});

</script>

Well, I would like to know which is the most efficient way to iterate the list since on the part of Back which is the domain I would return an empty list if there is no data or just the list if there is information (I do not speak of the page)

Although from what I have seen the response of Back, if the list is empty it should be a 200 since the list is returned but empty.

How could you control the empty response from FrontEnd?

    
asked by kik 03.08.2018 в 21:15
source

1 answer

1

First try to capture if there is an error in the request by adding the error function, then check if your list is null or empty and simply do not sample it or in any case send an error message.

<script>
$(document).ready(function(){

    $.ajax({
        type: 'GET',
        url: 'https://jsonplaceholder.typicode.com/posts',
        dataType: 'json',
        success: function(lista){
            console.log("OK");
            // validas si la lista es nula
            if(lista != null){
                // validas si la lista tiene elementos
                if(lista.lenght > 0){
                    $.each(lista, function(i, item){
                        console.log("item: " + item);
                    });
                }
            }
        },
        // aquí capturas cualquier error que venga del backend
        error: function(XMLHttpRequest, textStatus, error) { 
            console.log("status: " + textStatus); 
            console.log("error: " + error); 
        } 
    });

});

</script>

Now, you should bear in mind that as of version 3.0 of jQuery, the use of calls success , error , complete ,% done , fail and% has been changed always . So you would have to change your code to this structure:

var jqxhr = $.ajax( "https://jsonplaceholder.typicode.com/posts" )
  .done(function() {
    // equivalente a success
  })
  .fail(function() {
    // equivalente a error
  })
  .always(function() {
    // equivalente a complete
  });

Official jQuery documentation on jQuery.ajax ()

    
answered by 03.08.2018 в 21:32