我有这个检查英国邮政编码的功能。问题是它永远不会返回true
或false
- 仅undefined
。
function PostcodeAnywhere_Interactive_FindByPostcode_v1_00(Key, Postcode, UserName) {
var retval;
$.getJSON("https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/FindByPostcode/v1.00/json3.ws?",
{
Key: Key,
Postcode: Postcode,
UserName: UserName
},
function (response) {
// Test for an error
if (response.Items.length == 1 && typeof(response.Items[0].Error) != "undefined") {
// Show the error message
retval = false;
} else {
// Check if there were any items found
if (response.Items.length == 0){
retval = false;
} else {
retval = true;
}
}
});
return retval;
}
对我看起来应该总是返回true
或false
,所以我无法理解我哪里出错了。有人可以帮忙吗?是不是getJSON函数需要时间来执行?
答案 0 :(得分:9)
它返回undefined,因为$.getJSON
异步运行,因此在执行$.getJSON
的成功函数之前返回retval。如果您需要使用retval
,则必须在回调中调用使用它的函数
$.getJSON("https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/FindByPostcode/v1.00/json3.ws?",
{
Key: Key,
Postcode: Postcode,
UserName: UserName
},
function (response) {
// Test for an error
if (response.Items.length == 1 && typeof(response.Items[0].Error) != "undefined") {
// Show the error message
retval = false;
} else {
// Check if there were any items found
if (response.Items.length == 0){
retval = false;
} else {
retval = true;
}
//use retval
do_something_with_retval(retval);
}
});