duannai1883 2018-04-16 06: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 07: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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部