如何为ajax请求添加延迟以避免性能问题

时间:2016-04-05 13:32:58

标签: jquery ajax typeahead.js

我有一个函数可以在输入时返回AJAX中触发的一定数量的数据。每次它都会进入Oracle DB并获取数据并显示输出。

但是,只要我输入一个" long"字符串"你好,我的名字是",每当我输入一个键时,它会启动一个请求(一次10个请求),并且需要5秒才能得到1个请求响应。

这导致我的应用程序出现性能问题。我怎么能避免这个?

我已经尝试过无法正常工作的动态和延迟。我正在使用typeahead 2(typeahead-bs2.min.js)。

$( "#customer_description" ).typeahead({

 dynamic: true,
 delay: 5000,
 source: function (query, process) {
      $.ajax({
           url: '/data/customer.php',
           type: 'POST',
           dataType: 'JSON',
           //contentType: "text/json; charset=utf-8",                        
           data: {
                       all: query,
                   },
            success: function(data) {
                //console.log(data);
                process(data);
            }
        });
    }
});

2 个答案:

答案 0 :(得分:0)

如果我没有弄错你,你说你有类似搜索输入的东西会触发Ajax调用而你想阻止那个Ajax,所以它不会触发你按下的每个键。我是对的吗?

类似的东西:

    var timeOutId;
    $("#customer_description").typeahead({
        dynamic: true,
        source: function (query, process) {
            //if there's no ajax call running (the timeout was cleared)...
            if (!timeOutId || 'undefined' === typeof timeOutId) {
                timeOutId = setTimeout(ajaxCall, 300)
            }
        }
    });

    function ajaxCall() {
        $.ajax({
            url: '/data/customer.php',
            type: 'POST',
            dataType: 'JSON',
            //contentType: "text/json; charset=utf-8",                        
            data: {
                all: query,
            },
            success: function (data) {
                //console.log(data);
                process(data);
            },
            complete: function(){
              //when the ajax finishes (success or not) clear the interval
              clearTimeout(timeOutId);
            }
        });
    }

你可以改进这个代码做一个"静态类" (具有函数的对象)或伪类,但这取决于您。通过这种方式,您可以更改标志或其他内容的超时,您可以添加字符串长度检查...或者您能想到的任何内容。

答案 1 :(得分:0)

一旦用户停止输入,您可以在1.5 / 2秒的间隙后发出请求,并按照Sami的建议检查输入长度。

为了避免发送多个请求,您可以随时中止先前的请求并发送新请求。

 var start = new Date()
 ,end, request;

 $('input:text').on('change', function(){
  end = new Date();
  var input = $(this).val();
  var diff = (end - start)/1000;

  //checking for a 1.5 sec delay and input length
  //You can adjust the delay time, I have kept it as 1.5seconds
  if(diff > 1.5 && input.length > 5){
    if (request !== undefined){
      //aborting the previous request
      request.abort();
    }
    start = new Date();

    //storing the ajax request in a variable so that it can be aborted later when we fire a new request

    request = $.ajax({
      url: '/data/customer.php',
      type: 'POST',
      dataType: 'JSON',
      //contentType: "text/json; charset=utf-8",                        
      data: {
      all: query,
      },
      success: function(data) {
               //console.log(data);
                 process(data);
              }
    });
   }
 });