maxlength后的密钥上的Ajax请求 - maxlength后的数据错误

时间:2012-07-09 14:32:01

标签: javascript ajax jquery

我有一个ajax驱动的邮政编码查找。在字段达到所需的字符数(zip为5)后,在keyup上发生对服务的调用。但是,如果用户继续键入(6个以上字符),即使它们未在字段中显示,也会进行ajax调用并返回数据为空错误:

HTML

<input type="text" value="" id="billZipCode" name="billZipCode" class="smallInput coreAddrBill" maxlength="5">

的javascript

//show city/state on input maxlength
$("input#billZipCode").live("keyup", function( event ){
    if(this.value.length == this.getAttribute('maxlength')) {
        if ($(this).valid() == true ) {
            zipLookup(this, "USA");

        }
    }
});


//zip code lookup
function zipLookup(myField, myCountry) {


    $.ajax({
        type: "POST",
        url: postalCodeLookupURL,
        dataType:"text json",
        data: { postalcode: $(myField).val(), country: myCountry },
        success: function(data) {
            var isError = data.isError;
            var city = data.city;
            var juris = data.juris;
            if(isError == "false"){

                    $(myField).parent().next('div').find('input').val(city);
                    $(myField).parent().next('div').next('div').find("select option[value='" + juris +"']").attr('selected', 'selected');
                    $("#createAccount").validate().element($(myField).parent().next('div').find('input'));
                    $("#createAccount").validate().element($(myField).parent().next('div').next('div').find("select"));

            }


        },
        error: function(){
        alert('failure');
      }

     });


}

1 个答案:

答案 0 :(得分:0)

//Live is depreciated,use delegate and some other tweaks
    $("body").delegate("input#billZipCode","keyup", function( event ){
        if($(this).val().length >= $(this).attr('maxlength')) {          
                zipLookup(this, "USA");

        }else{
         alert('Max reached');
      }
    });