Pass a getJSON value to a variable

Asked

Viewed 354 times

0

I have the following code:

    $('#aprovados').click( function(){
  var job = $.getJSON($(this).attr("data-ajax-info-job"),
    function(jobinfo){
       return jobinfo }
  );
  console.log(job)
  });

The idea was to return my json data that comes from my backend but I receive as if it were a log of the request. How could I change this code to only receive the json I need?

  • getJSON is asynchronous, so the.log(job) console will not wait for Ajax to return.

  • That is, you will need to work with the data inside the getJSON function

  • I understood but there was some way I could get that amount?

  • with $.ajax is possible using async, but is not recommended :/

1 answer

1


The function $.getJSON() is asynchronous, the return of this call will not be immediately resolved...you must "observe" the callback if you want to run something only after having a return.

var job; // reserve a variável
// faça o pedido (requisição)
$.getJSON($(this).attr("data-ajax-info-job"),function(jobinfo) {
    // atribuir
    job = jobinfo;
})

Or you can link the return to a function:

function executarAlgumaTarefa(param) {
    console.log(param)
}
// faça o pedido (requisição)
$.getJSON($(this).attr("data-ajax-info-job"),executarAlgumaTarefa)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.