如何通过多个函数处理ajax对div共享的慢响应

Hem*_*ote 5 javascript ajax jquery

我有一个div.

<div id="test"></div>
Run Code Online (Sandbox Code Playgroud)

功能很少.

fun1()
{
  $('#test').html('');
  $.ajax(function(){
     url : abc/index;
     success : function(response){
      $('#test').html(response);
     }
  });
}
fun2()
{
     $('#test').html('');
     $.ajax(function(){
     url : abc/getDetail;
     success : function(response){
      $('#test').html(response);
     }
  });
}
fun3()
{
 $('#test').html('');
  $.ajax(function(){
     url : abc/getUser;
     success : function(response){
      $('#test').html(response);
     }
  });
}
Run Code Online (Sandbox Code Playgroud)

函数调用不同的按钮单击.

btn1.click(fun1())
btn2.click(fun2())
btn3.click(fun3())
Run Code Online (Sandbox Code Playgroud)

当btn1,btn2,btn3一个接一个地按下时,我可以看到div'test'在一段时间'fun2'响应后包含第一个'fun1'响应,依此类推.

我知道原因,因为我的ajax响应很慢,这就是它发生的原因.

当某人点击btn1并在获得fun1的响应之前,请按btn2.在这种情况下,我只想加载fun2响应.如果fun2正在制作延迟想显示空白页面.

按下按钮,我正在考虑杀死剩余的ajax请求.但同时我的其他ajax请求也在进行,我不想杀死那些.因此杀死其他ajax请求对我不起作用.什么是其他解决方案.

Ewa*_*wan 1

好的,你有两个问题

1:当您实际上只想处理最后一个请求时,您正在触发多个请求

2:每个事件都会更新屏幕,无论发生了什么

我建议你分别解决这两个问题。

首先,为您的响应添加回调函数。这将允许您在更新页面之前检查条件(例如“还发生了其他事情吗?”)。这使您有机会丢弃第一个响应。

其次,您需要首先处理多个请求的发送。您可以在单击第二个按钮时取消它们(但它们仍将在服务器上处理)或者:您可以添加一个计时器而不立即发送请求。

单击按钮时启动计时器,然后说 200ms?然后,触发请求并处理响应。

如果在 200 毫秒过去之前再次点击,请忘记第一个计时器并启动新的计时器。

或者,您可以通过停用按钮并仅在收到响应后重新激活来防止用户在发送请求后单击按钮。

例如:(我知道全局变量有点粗糙)

    var btnLastPressed =0
    fun1()
    {
      btnLastPressed = 1;
      $('#test').html('');
      $.ajax(function(){
         url : abc/index;
         success : function(response) { finished(1,response);}
      });
    }

    function finished(btn, response){
       if(btnLastPressed==1){
          $('#test').html(response);
       }
    }
Run Code Online (Sandbox Code Playgroud)