weixin_33735077 2018-09-04 20:15 采纳率: 0%
浏览 50

限制每个输入的ajax调用

I have a working ajax call that I've made which sends a value to an endpoint for every input change. SO if the user is typing, it sends the call per keystroke.

I put a setTimeout around it for 2 seconds, which delays the call just fine. But the problem is it still sends a call for every keystroke.

I want to get it to where, after 2 seconds, it sends a call for what's been typed so far. If the user starts typing again maybe it would set again.

I"m just trying to send fewer keystrokes and make it to where when the user stops typing there's just a slight delay and call.

Here's the call now:

$('#input').on('input', function() {
  let _this = $(this);


  if (_this.val() === '') {
    return;
  } else {

    const searchResult = $(this).val();
    console.log(searchResult);
    //if I type "PLANT" the console shows "P" "PL" "PLA" "PLAN" "PLANT"

    //after 2 seconds, send searchResult via ajax
    setTimeout(function () {
        $.ajax({ url: '/endpoint', 
          data: {
            search_result:searchResult
          },
          "_token": "{{ csrf_token() }}",
          type: "POST", 
          success: successHandler 

        });
    }, 2000);
  }
});
  • 写回答

1条回答 默认 最新

  • weixin_33686714 2018-09-04 22:54
    关注

    You should debounce the ajax call. The idea is that the timeout is cleared if the user enters another value. That way the ajax call will only be made once after the user has stopped typing for the given timeout period (2 seconds for your case). That would look something like this:

    var timeout;
    
    $('#input').on('input', function() {
      let _this = $(this);
    
    
      if (_this.val() === '') {
        return;
      } else {
    
        const searchResult = $(this).val();
        console.log(searchResult);
        //if I type "PLANT" the console shows "P" "PL" "PLA" "PLAN" "PLANT"
    
        if (timeout) {
          clearTimeout(timeout);
        }
        
        //after 2 seconds, send searchResult via ajax
        timeout = setTimeout(function () {
            $.ajax({ url: '/endpoint', 
              data: {
                search_result:searchResult
              },
              "_token": "{{ csrf_token() }}",
              type: "POST", 
              success: successHandler 
    
            });
        }, 2000);
      }
    });

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度