简体   繁体   English

如何防止重复的AJAX通话?

[英]How to prevent duplicated AJAX call?

I'm currently building a simple AJAX call application which will show the result of a textbox after typing some texts inside it: 我目前正在构建一个简单的AJAX调用应用程序,该应用程序在其中输入一些文本后将显示文本框的结果:

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

$(document).ready(function(e) {

    $("input[name=html]").keyup(function(e) {
        if(this.value.length > 1) {        
            e.preventDefault();
            var form = $(this).closest('form');
            var form_data = form.serialize();
            var form_url = form.attr("action");
            var form_method = form.attr("method").toUpperCase();
            delay(function(){
                $("#loadingimg").show();
                $.ajax({
                    url: form_url, 
                    type: form_method,      
                    data: form_data,     
                    cache: false,
                    success: function(returnhtml){                          
                        $("#result").html(returnhtml); 
                        $("#loadingimg").hide();                    
                    }           
                });    
            },1000);
        }
    });

});

Fiddle Demo 小提琴演示

As you can see from the demo above, for instance if you type test , test1 or test2 or any word as long as their length is longer than one then it'll make an AJAX call. 从上面的演示中可以看到,例如,如果您键入testtest1test2或任何单词,只要它们的长度大于1,则它将进行AJAX调用。

My question is that is there any way that allow me to prevent duplicate AJAX call? 我的问题是,有什么办法可以防止重复的AJAX调用? For example if I type test in the textbox again, it'll immediately show test in the div without making another AJAX call to fetch the result again. 例如,如果我再次在文本框中输入test ,它将立即在div中显示test ,而无需再次调用AJAX再次获取结果。 Thank you very much in advance. 提前非常感谢您。

You just need to cache previous results and, before making the ajax call, check the cache to see if you already have that result in the cache. 您只需要缓存先前的结果,并且在进行ajax调用之前,请检查缓存以查看缓存中是否已经有该结果。

In Javascript, one usually uses an object for a cache: 在Javascript中,通常将一个对象用于缓存:

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

// create cache for ajax results
// the key is the form_data
// the value is whatever the ajax call returns
var ajaxCache = {};

$(document).ready(function(e) {

    $("input[name=html]").keyup(function(e) {
        if(this.value.length > 1) {        
            e.preventDefault();
            var form = $(this).closest('form');
            var form_data = form.serialize();
            // check the cache for a previously cached result
            if (ajaxCache[form_data]) {
                 // this uses delay, only so that it clears any previous timer
                 delay(function() {
                     $("#result").html(ajaxCache[form_data]); 
                     $("#loadingimg").hide();
                 }, 1);
            } else {
                var form_url = form.attr("action");
                var form_method = form.attr("method").toUpperCase();
                delay(function(){
                    $("#loadingimg").show();
                    $.ajax({
                        url: form_url, 
                        type: form_method,      
                        data: form_data,     
                        cache: false,
                        success: function(returnhtml){                          
                            $("#result").html(returnhtml); 
                            // put this result in the cache
                            ajaxCache[form_data] = returnhtml;
                            $("#loadingimg").hide();                    
                        }           
                    });    
                },1000);
            }
        }
    });
});

Working demo: http://jsfiddle.net/jfriend00/P2WRk/ 工作演示: http : //jsfiddle.net/jfriend00/P2WRk/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM