同步AJAX调用之前的代码在Chrome中冻结

我想在执行同步AJAX调用时将按钮更改为加载状态。 除了jQuery代码(在Chrome中),将按钮更改为加载状态冻结,直到AJAX调用完成。 因此,在de ajax调用后,加载状态将显示1 ms。

我在JSFiddle中创建了一个示例来检查它。 (签入Chrome)
http://jsfiddle.net/b8w9hf01/

$('.button').on('click', function() { // change button text (DOESN'T SHOW) $(this).html('Loading..').delay(10); // do async call $.ajax({ url: 'http://echo.jsontest.com/insert-key-here/insert-value-here/key/value', async: false, dataType: "json", success: function(poResponse){ console.log(poResponse); } }); // change button text $('.button').html('Done'); // put Click here back after a second, for repeation of the test setTimeout(function() { $('.button').html('Click here'); }, 1000); }); 

将其更改为异步调用将起作用,但现在将会有很多工作。 有人有解决方案吗? 谢谢!

有关说明,您可以在此处查看 :

调用之前的代码正在运行,但这并不意味着您将立即看到结果。 如果调用是真正完全同步的,则在$ .ajax调用完成之后才可能发生窗口更新。

如果您坚持使用同步的ajax调用(实际上已弃用),则可以执行以下操作:

 // change button text $(this).html('Loading..'); // do async call setTimeout(function () { $.ajax({ url: 'http://echo.jsontest.com/insert-key-here/insert-value-here/key/value', async: false, dataType: "json", success: function (poResponse) { console.log(poResponse); } }); // change button text $('.button').html('Done'); }, 20); 

演示

更新

为了记录,异步版本在这里非常简单:

 // change button text $(this).html('Loading..'); // do async call $.ajax({ url: 'http://echo.jsontest.com/insert-key-here/insert-value-here/key/value', async: true, dataType: "json", success: function (poResponse) { // change button text $('.button').html('Done'); console.log(poResponse); } }); 

演示

这是代码,它将创建预期的行为,你想要的按钮:

 $('.button').on('click', function() { // change button text (DOESN'T SHOW) $(this).html('Loading..'); // Let's disable the button to prevent further clicks. $(this).('attr','disabled'); // do async call $.ajax({ url: 'http://echo.jsontest.com/insert-key-here/insert-value-here/key/value', dataType: "json", success: function(poResponse){ //Ajax is successful, we can enable the button again. setTimeout(function() { $(this).removeAttr('disabled'); $(this).html('Done'); }, 1000); }, error: function(){ //So there was an error, let's enable the button & let the user know (so wise of us) setTimeout(function() { $(this).removeAttr('disabled'); $(this).html('Error occured, Try Again'); }, 1000); } }); // put Click here back after a second, for repeation of the test setTimeout(function() { $('.button').html('Click here'); }, 3000); });