duanju9104 2015-08-15 13:35
浏览 321
已采纳

jQuery ajax beforeSend干扰.done()

In a website I have several ajax-parts that are loaded by events, mostly clicks. To inform the visitor a loading partial is shown. This works nice most of the time, but sometimes the ajax call is receiving the respons so quick it interferes with the beforeSend.

My typical structure looks like this:

$(document).on('click', '.handler', function() { 
  var target = $(this).attr('data-targetElement');

  $.ajax({
    url: '/ajax.php?someParameter=hasValue',
    beforeSend: showLoading(target)
  })
  .done(function(response) { 
    console.log('Hi there, I\'m done!');
    $('#' + target).html(response);
  });
});

// This is in a function because it's used by all ajax-calls
function showLoading(target) { 
  $('#' + target).html('My loading message');
}

The problem is, when I'm inspecting console messages, that the loading message is still shown even though the .done() was reached, because Hi there, I'm done! is shown.

So it looks beforeSend doesn't seem to have reached a completed state or something like that causing it to 'freeze', because the content in the targetElement is not updated with the response for the ajax-call.

I'm not sure how to solve to this. Any suggestions?

Update, Sorry for the typo, I just typed the exemplary code in here...

  • 写回答

2条回答 默认 最新

  • duanbei2914 2015-08-15 13:48
    关注
    1. At first, you need to fix all syntax errors in your code. Remove ; in the middle of the statement.

      $.ajax({
        beforeSend: showLoading(target);
        //                             ^ SYNTAX ERROR
      })
      
    2. When you write showLoading(target) you call the showLoading() function immediately.

      If you need to set pass it as a callback with parameters, you need to pass a function, that returns your callback.

      beforeSend: function() {
          showLoading(target);
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示