gpt4 book ai didi

javascript - 同步 AJAX 调用之前的代码在 Chrome 中卡住

转载 作者:行者123 更新时间:2023-11-29 10:42:33 27 4
gpt4 key购买 nike

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

我在 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);
});

将其更改为异步调用会奏效,但目前会有很多工作要做。有人有解决方案吗?谢谢!

最佳答案

解释可以查看here :

The code before the call is running, but that doesn't mean you will see the result immediately. If the call is truly and completely synchronous, the window update might not happen until after the $.ajax call completes.

如果您坚持使用同步 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);

Demo

更新

郑重声明,这里的异步版本非常简单:

// 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);
}
});

Demo

关于javascript - 同步 AJAX 调用之前的代码在 Chrome 中卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com