Pass value from a getJSON to a variable

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 get it as if it were a log of the request. How could I change this code to just get the json I need?

    
asked by anonymous 17.03.2018 / 00:04

1 answer

1

The function $ .getJSON () is asynchronous, the return of this call will not be immediately resolved ... you you should "notice" the callback in case you want to execute something only after 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 bind 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)
    
17.03.2018 / 00:28