Waiting for JSON data processing

Is there any way to wait for the jQuery getJSON method?

I want to analyze the data obtained using this function, and simply return false / true if a specific row is contained. But due to asynchronous data processing, it is not so simple. Here is the code snippet:

contained = false; $.getJSON(URL, function ( data ) { $.each( data, function( i, item ) { if ( item.Info.code == code ) contained = true; }); }); 

After this code, the function in which this code is placed returns a value of "containing", which is mostly false, since getJSON is not yet complete.

+4
source share
3 answers

You can try to execute a synchronous request, for example:

  $.ajax({ type: "GET", url: "www.foo.com", data: data async: false, dataType: "json" }); 
+6
source

The correct solution does not make it synchronous (this is possible, but not recommended). It uses the callback appropriately. Asynchronous programming is addictive, but worth it.

Instead:

 function foo() { ... contained = false; $.getJSON(URL, function ( data ) { $.each( data, function( i, item ) { if ( item.Info.code == code ) contained = true; }); }); // Do something with contained } 

make:

 function getContained(containedCallback) { $.getJSON(URL, function(data) { var contained = false; $.each( data, function( i, item ) { if ( item.Info.code == code ) contained = true; }); containedCallback(contained); } ); } function foo() { ... getContained(function(contained) { // Do something with contained }); } 
+8
source

Thanks for your reply. I just installed the process synchronously:

 $.ajaxSetup({'async': false}); 

After that I used my code. Work just fine!

Additional jQuery Ajax options here

+5
source

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


All Articles