更新的 UI 在同步 ajax 调用之前未显示

2024-03-07

我有 2 个 JavaScript 函数,它们依次调用。喜欢跟随。

updateUI(event);
syncCall();

function updateUI(event) {
  formSubmitBtn = $(event.target).find('[type=submit]:not(".disabled")');
  formSubmitBtn.attr('disabled', 'disabled');
  var loadingText = I18n.t('Submitting');
  formSubmitBtn.val(loadingText).text(loadingText);
}

function syncCall(){
$.ajax({
    async: false,
    dataType: 'json',
    type: 'GET',
    url: '/calls/synccall',
    success: function (json) {
      userIsSignedIn = json.is_signed_in;
    }
  });
}

我正在同步 ajax 调用之前更新 UI 元素。但 UI 更改未显示。当我尝试调试代码时,它工作正常。


我可以想象你的代码正在做类似的事情

var userIsSignedIn;
updateUI(event);
syncCall();
nextThing(userIsSignedIn);
anotherThing();
moreThings();

对syncCall进行简单的更改 - 称为asyncCall,以免混淆

function asyncCall(cb){
    $.ajax({
        dataType: 'json',
        type: 'GET',
        url: '/calls/synccall',
        success: function (json) {
          cb(json.is_signed_in);
        }
    });
}

你的代码重写:

updateUI(event);
asyncCall(function(userIsSignedIn) {
    nextThing(userIsSignedIn);
    anotherThing();
    moreThings();
});

注意缺少var userIsSignedIn;必需的

对于改善最终用户体验来说确实是一个小小的改变

第二种选择是将您提供的所有代码包装在标记的函数中async

async function doThings() {
    updateUI(event);
    let userIsSignedIn = await ajaxCall(); // see below
    nextThing(userIsSignedIn);
    anotherThing();
    moreThings();
}

并返回一个 PromiseajaxCall(什么是syncCall)

function ajaxCall(){
    return $.ajax({
        dataType: 'json',
        type: 'GET',
        url: '/calls/synccall'
    }).then(json => json.is_signed_in);
}

通过转译器(如 babel)运行它以生成应在 Internet Exploder 和类似的“向后”浏览器上运行的代码

总结:最后你有两个选择

  • 使用 async:false 并具有垃圾用户体验
  • 拥抱异步并编写适合 21 世纪的代码
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更新的 UI 在同步 ajax 调用之前未显示 的相关文章

随机推荐