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

标签 javascript jquery ajax 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);
});

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

最佳答案

解释可以查看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/

相关文章:

javascript - 在网页上播放音频而不会因页面重新加载而中断

javascript - 事件调用回调即调用callback

javascript - ajax 提交带有漂亮 URL 的请求

javascript - 单击显示按钮时显示表中找到的所有名称

ajax - 更新与点击事件触发 JQuery AJAX 请求关联的 HTML 元素

javascript - Adobe Animate CC Canvas 鼠标在舞台上的操作缓慢且间歇性

javascript - 字符串化 HTML 中的空格导致无效表达式

javascript - AngularJS 指令 - 当输入文件更改时调用特定函数

javascript - jQuery Content() 查找以 MB 为单位的权重

javascript - 如何异步运行函数 (XMLHttpRequest)