我有一个 ajax 驱动的邮政编码查找。在字段达到所需字符数(zip 为 5)后,对服务的调用发生在 keyup 上。但是,如果用户继续输入(超过 6 个字符),即使他们没有显示在字段中,也会进行 ajax 调用并返回数据为 null 错误:
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');
}
});
}