我正在查询zippopotam.us邮政编码查询服务以返回城市信息。这个独立的代码块可以工作:
$("#studentPostCode").blur(function() {
var zip_in = $(this);
if (zip_in.val().length == 5) {
$.ajax({
url: "http://api.zippopotam.us/SE/" + zip_in.val(),
cache: false,
dataType: "json",
type: "GET",
success: function(result, success) {
// Accept the first result
var places0 = result['places'][0];
var placeName = places0['place name'];
$("#studentCity").val(placeName);
},
error: function(result, success) {}
});
}
});
但是,当我尝试重构以便可以在其他地方使用它时,它就会中断。我的努力:
//calls
$("#studentPostCode").blur(function() {
var pCode0 = $(this);
var myCity0 = getPlaceFromPostCode(pCode0);
$("#studentCity").val(myCity0);
});
$("#guardian1PostCode").blur(function() {
var pCode1 = $(this);
var myCity1 = getPlaceFromPostCode(pCode1);
$("#guardian1City").val(myCity1);
});
//function refactored as:
$(function getPlaceFromPostCode(pCodeX) {
var zip_in = pCodeX;
if (zip_in.val().length == 5) {
$.ajax({
url: "http://api.zippopotam.us/SE/" + zip_in.val(),
cache: false,
dataType: "json",
type: "GET",
success: function(result, success) {
// Accept the first result
var places0 = result['places'][0];
var placeName = places0['place name'];
return placeName;
},
error: function(result, success) {}
});
}
});
这将返回“ placeName”为未定义。我要去哪里错了?
return placeName;
成功处理程序中的语句将被忽略,因为函数本身是异步调用的,并且该getPlaceFromPostCode
方法不返回任何内容。尝试以下方法:
function getPlaceFromPostCode(pCodeX, cityCallback) {
//... the $.ajax call
success: function(result, success) {
// Accept the first result
var places0 = result['places'][0];
var placeName = places0['place name'];
cityCallback(placeName);
}, //... etc
}
然后调用该函数(也可能是一个更简单的速记形式,而不是一个成熟的函数):
getPlaceFromPostCode(pCode1, function(city){
$("#guardian1City").val(city);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句