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

pas*_*ert 3 javascript ajax jquery google-chrome

我想在执行同步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);
});
Run Code Online (Sandbox Code Playgroud)

将其更改为异步调用可能会起作用,但目前将非常有用。有没有人有解决方案?谢谢!

GôT*_*ôTô 5

有关说明,您可以在这里检查:

调用之前的代码正在运行,但这并不意味着您会立即看到结果。如果调用是真正且完全同步的,则直到$ .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);
Run Code Online (Sandbox Code Playgroud)

演示版

更新资料

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

// 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);
    }
});
Run Code Online (Sandbox Code Playgroud)

演示版

  • @pascalvgemert您最好先开始:) (3认同)