Jquery ajax with asynchronous false value prevents previous display changes in Chrome

so i have the following:

$('.something').click(function(){ $('body').html(''); $.ajax({ url: 'someurl', dataType: 'json', async: false, success: function(data){ //do stuff alert('yo'); } }); return false; }); 

in Firefox, the body will become empty before the warning "yo" is correct ... But then in Chrome the body will only become empty after ajax and the warning "yo" are successful, even if $ ("body"). html ('') is executed before ajax .... this is due to the async setting, which is set to false ... if it is true, it will also work correctly in chrome

Is there a way to get a call to $ ('body'). html () is called before the start of the ajax call in Chrome, keeping the async flag set to false?

It would also be advisable not to set a timeout

+6
source share
2 answers

Are you sure you saw the page becoming blank before calling AJAX with this code? This should not happen in any browser.

The browser window does not refresh at all while the script is running, so a synchronous call blocks all updates.

To update the browser to an AJAX call, use setTimeout , which will return the control to the browser before sending the request:

 $('.something').click(function(){ $('body').html(''); window.setTimeout(function() { $.ajax({ url: 'someurl', dataType: 'json', async: false, success: function(data){ //do stuff alert('yo'); } }); }, 0); return false; }); 

Note. This, of course, means that you cannot use the result of the query in the return value of the function if it was an intent with a synchronous call. If you need a synchronous event handler, you cannot upgrade your browser to an AJAX request.

+5
source

Quote from http://api.jquery.com/jquery.ajax/

async (default: true) Type: Boolean By default, all requests are sent asynchronously (i.e., by default, this value is true). If you need synchronous requests, set this parameter to false. Cross-domain requests and dataType: jsonp requests do not support synchronous operation. Please note that synchronous requests can temporarily block the browser, disabling any actions while the request is active. Starting with jQuery 1.8, the use of async: false with jqXHR ($ .Deferred) is deprecated; you should use success / error / full callback parameters instead of the corresponding jqXHR object methods such as jqXHR.done () or deprecated jqXHR.success ().

Perhaps you can try the following: Cleanse the body with $.ajax beforeSend: function () {}

 $('.something').click(function() { $.ajax({ url: 'someurl', dataType: 'json', async: false, beforeSend: function (){ $('body').html(''); }, success: function(data){ //do stuff alert('yo'); } }); return false; }); 
+1
source

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


All Articles