javascript函数没有返回正确的值

时间:2012-02-13 16:23:40

标签: javascript jquery function

我有这个检查英国邮政编码的功能。问题是它永远不会返回truefalse - 仅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;

}

对我看起来应该总是返回truefalse,所以我无法理解我哪里出错了。有人可以帮忙吗?是不是getJSON函数需要时间来执行?

1 个答案:

答案 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);
        }
    });