问题
I'm wanting to run AJAX to get some URL data, build an object from the data and assign it to a global object variable. So I know I need to run a synchronous ajax request. (Right?) Well I also want to make use of the beforeSend setting to give my users a loading screen. (I probably should be asking first, is beforeSend the only way to achieve that?) How might I combine the benefits sync and async?
async:
$.ajax({
url:'scripts/scripts.php?call=page&url='+thisurl, /*local*/
dataType:'html',
beforeSend:function(){
$('#display').html('<div class="loading"></div>');
},
success:function(data, textStatus, jqXHR){
/*local*/ myobj = getMyObj(data); $('#display').html(myobj);
},
error:function(jqXHR, textStatus, errorThrown){ }
});
sync:
$.ajax({
url:'scripts/scripts.php?call=page&url='+thisurl, /*local*/
dataType:'html',
async:false,
success:function(data, textStatus, jqXHR){
/*global*/ myobj = getMyObj(data);
}
});
$('#display').html(myobj);
sorry if this doesn't make sense
回答1:
Ehm, well, it's pretty obvious that if you want to display something before a synchronous ajax function you do:
$('#display').html('<div class="loading"></div>');
$.ajax({
url:'scripts/scripts.php?call=page&url='+thisurl, /*local*/
dataType:'html',
async:false,
success:function(data, textStatus, jqXHR){
/*global*/ myobj = getMyObj(data);
}
});
$('#display').html(myobj);
On the other hand why use a synchronous Ajax function, it's a really bad idea, use promises instead, or something like:
var Ajax = $.ajax({
url:'scripts/scripts.php?call=page&url='+thisurl,
dataType:'html'
});
//do something later
$("#mybutton").on('click', function() {
Ajax.done(function(data) { //if/when the ajax function is completed
$('#display').html(data);
});
});
Or stick the ajax in a seperate function and run that the same way, there are many options other than synchronous Ajax calls!
回答2:
Chances are you don't really want to do a synchronous AJAX request. From the jQuery.ajax documentation:
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active
A better practice is to make an async request and put up a spinner to let the user know you are retrieving data for them.
来源:https://stackoverflow.com/questions/9952242/performing-synchronous-and-asynchronous-ajax-at-the-same-time