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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵