Hello. At the beginning of the js script, I need to send an ajax request, retrieve data from it, and only then continue with the script. Now I have the following code: var user_data = getdata (count); The getdata method sends a get request to the script. The problem is that when the user_data variable is needed, it is still empty, because we did not receive a response from the server. How to act in this case? getdata method returns an array from JSON.parse
2 answers
You can use $.when and its promise https://api.jquery.com/jquery.when/
If only one deferred object is passed to $.when() , it will simply return its promise version. In addition to deferred-objects in $.when() you can specify any other js-objects. jQuery will always determine their state as successful.
Example:
$.when( $.ajax("test.aspx") ).then(function(data, textStatus, jqXHR){ alert( jqXHR.status ); // выводит 200 }); Accordingly, you shove your request in when , and after its execution you finish your dirty work:
$.when( $.ajax( "/page1.php" ) ).done(function( data ) { // делаете что-то что вам нужно сделать // var response = data[ 0 ] + data[ 1 ]; // alert(response); // ... // ... }); ajaxreturns promise, no needwhenuse - Grundy- one@Grundy yes, probably
whenit makes sense when you need to run asynchronously several at the same time - Alexey Shimansky
|
Solved the problem by concluding everything you need when in $.get("имя скрипта" , { user_number: count} ).done(function( data ) {
|
falsewill solve the problemxhr.open('POST', url, false);. The script will not go further until the request is fulfilled - Mr. Black