我有太多的AJAX请求

时间:2015-12-29 01:10:14

标签: jquery optimization xmlhttprequest

这里有一个高级问题(像我这样的菜鸟哈哈)。当我点击导航项目以显示与该导航项目相关的内容时,我正在编写一个发出AJAX请求的应用程序。到现在为止还挺好。每次点击一次请求,没关系。

当我通过JS发出AJAX请求时出现问题,第一个AJAX请求是导航项中的请求。如果你愿意,那就是一种开始。请求中的请求o.O

我提交给您的代码的工作是在指定的延迟后,当密钥启动时检索数据。问题是,即使存在延迟,也会对按下的每个键发出请求。如何减少请求数量?

var delay = (function(){
      var timer = 0;
      return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
      };
    })();

$("#browse-foods-search-input").keyup(function(){
    delay(function(){ 

        // This IF checks if the field is empty. If so, the default content is loaded
        if ($("#browse-foods-search-input").val() == "")
        {
            $.ajax({
                type: "GET",
                url: "ajaxLoad.php?action=food-journal&mod=browse-foods&send_header=0",
                success: function(response) {
                    $(".browse-foods-container").html(response.html);
                    eval($(response.js).text());                           
                }
            });
        }
        else {    // This ELSE creates the request for searching
           $.ajax({
               type: "GET",
               url: "ajaxLoad.php?action=food-journal&mod=browse-foods&search_key="+$("#browse-foods-search-input").val(),
               success: function(response) {
                    $(".browse-foods-container").html(response.html);
                    eval($(response.js).text());
               }
             });   
        }   
    }, 500 );        
});  

请注意,上面的代码按预期工作,但我有兴趣优化我的代码。欢迎任何问题,评论和批评!

0 个答案:

没有答案