5次击键后AJAX调用未触发

时间:2015-10-21 16:49:08

标签: javascript jquery ajax exacttarget ampscript

为什么在开火前需要超过5次击键?

$( document ).ready(function() {

  $("#zipcode").on("keyup", function(event) { // keyup function

    if(this.value.length == 5){ // if 5 time keyup then fire the ajax 

        var zicpcode= $("#zipcode").val(); // get the value of zipcode

        $.ajax({
            url: "http://pages.em.essilorusa.com/page.aspx?QS=773ed3059447707d2a7242227e94bba8efcc7ce6da09facd&zip="+zicpcode,
            type: "get", //send it through get method
             success: function(results) {
                var res = results.substring((results.indexOf("<rs1>")+5),results.indexOf("</rs1>"));
                var splitted = res.split("|");
                var distinct = [];
                $.each(splitted , function(i, el){
                    if($.inArray(el, distinct ) === -1) 
                        distinct.push(el);
                });
                $("#zipcode").autocomplete({ source: distinct }); 
              },
        });
    }

  });

});

它工作正常,但有一个额外的击键或退格。

1 个答案:

答案 0 :(得分:0)

$(document).ready(function() {
    splitted = []; // Inialization empty array 
    $("#zipcode").autocomplete({
        source: splitted
    }); //Inialization for enabling the feature of Auto-complete
    $("#zipcode").keyup(function(event) {
        if (this.value.length == 5) {


            var zicpcode = $("#zipcode").val();
            $.ajax({
                url: "http://pages.em.essilorusa.com/page.aspx?QS=773ed3059447707d2a7242227e94bba8efcc7ce6da09facd&zip=" + zicpcode,
                type: "get", //send it through get method
                async: false,
                success: function(results) {
                    var res = results.substring((results.indexOf("<rs1>") + 5), results.indexOf("</rs1>"));
                    var splitted = res.split("|");
                    $("#zipcode").autocomplete({
                        source: splitted
                    });
                },
            });

        }
    });
});