同步AJAX调用之前code冻结在ChromeAJAX、code、Chrome

2023-09-10 18:05:39 作者:乖一点就抱你

我要当执行同步AJAX调用改变一个按钮,加载状态。除了jQuery的code(在Chrome),其改变按钮,直到AJAX调用加载完成状态冻结。所以加载状态将显示为德AJAX调用后,也许1毫秒。

I want to change a button to a loading state when a synchronous AJAX call is being executed. Except the jQuery code (in Chrome) that change the button to loading state freezes until the AJAX call is finished. So the loading state will show up for maybe 1 ms after de ajax call.

我创建了的jsfiddle一个例子来看看。 (请在Chrome)的 http://jsfiddle.net/b8w9hf01/

I created an example in JSFiddle to check it out. (Check in 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);
});

将其更改为一个异步调用会的工作,但将是大量的工作现在。有没有人有一个解决方案吗?谢谢!

Changing it to an async call would work, but will be to much work for now. Does anyone has an solution? Thanks!

推荐答案

有关的解释,你可以检查这里:

For the explanation, you can check here:

在调用之前的code上,但这并不意味着你会   马上看到结果。如果呼叫是真实,完整   同步,窗口更新可能不会发生,直到之后的$阿贾克斯   调用完成。

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调用,这实在是德precated,您可以执行以下操作:

If you insist on using a synchronous ajax call, which is really deprecated, you can do the following:

// 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

Update

有关的记录,异步版本是非常简单的在这里:

For the record, the async version is really simple here:

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