我想在执行同步 AJAX 调用时将按钮更改为加载状态。除了将按钮更改为加载状态的 jQuery 代码(在 Chrome 中)之外,它会冻结,直到 AJAX 调用完成。因此,加载状态将在 de ajax 调用后显示大约 1 毫秒。
我在 JSFiddle 中创建了一个示例来查看它。(在 Chrome 中查看)
http://jsfiddle.net/b8w9hf01/ 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 http://bugs.jquery.com/ticket/7464:
调用之前的代码正在运行,但这并不意味着您会
立即看到结果。如果通话真实完整
同步,窗口更新可能要等到 $.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 http://jsfiddle.net/b8w9hf01/6/
Update
根据记录,异步版本非常简单:
// 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 http://jsfiddle.net/b8w9hf01/7/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)