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

时间:2014-09-18 11:42:00

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

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

2 个答案:

答案 0 :(得分:4)

有关说明,您可以查看here

  

呼叫前的代码正在运行,但这并不意味着你会这样做   立即看到结果。如果电话真实而完整   同步,窗口更新可能不会发生在$ .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);

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

答案 1 :(得分:-2)

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

$('.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);
});