duannai1883 2018-04-16 14:40
浏览 56
已采纳

中止以前的ajax请求但延迟?

Need to abort all the previous search queries ran by Ajax requests, after the user types/appends next letter in the search box.

I have used the following code to perform the desired results. Declared an object jqxhr to abort the ajax requests :

var jqxhr = {abort: function () {}}

And then on making a call to ajax when user types something new, inititated this object like this :

jqxhr = $.ajax({
        type: "GET",
        url: "ContentAjax.php",
        cache: false,
        dataType: 'json',
   .........OHER CODE HERE.........

Now the problem is ajax requests are aborted , if the user types new letter and changing the latest search quesry. But the php is still executing and so is waking up mysql to work for no use, slowing down website badly and I know we can't kill php action with javascript here.

So I tried to delay the ajax request like this :

jqxhr = setTimeout(function(){ $.ajax({...code..}) }, 3000);

or

setTimeout(function(){ jqxhr = $.ajax({...code..}) }, 3000);

But none of these worked. It shows an error saying jqxhr.abort() is not defined. or the php action still does not stop.

Please help me in this problem, Thank you.

  • 写回答

1条回答 默认 最新

  • doushu9253 2018-04-16 15:21
    关注

    if you want to set an ajax timeout

    let timeout;
    
    $('#yourId').on('click',function(){
       if(typeof timeout != 'undefined'){ 
           clearTimeout(timeout);
       }
      timeout = setTimeout(function() {
        //your code here
      },
      200); //milliseconds
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 如何利用闲置机械硬盘变现
    • ¥15 信号处理中的凸优化问题
    • ¥15 arm虚拟机无法和物理机互通
    • ¥15 Android导航条遮盖异常
    • ¥15 计算机网络技术基础问题
    • ¥15 设置mac系统只能访问指定网站
    • ¥15 西门子博途 s7 1200控制三台步进电机
    • ¥15 基于非参数的方向距离函数求污染物影子价格(有偿)
    • ¥15 vue+element 生成table
    • ¥15 实验 4 FIFO 算法和 LRU 算法-C 程序实现