通过从包含ajax调用的Javascript函数返回来获取数组值

时间:2015-02-04 18:07:12

标签: javascript jquery ajax

我正在尝试读取从包含ajax调用的函数product_info返回的getproductInfo数组,但我仍然在console.log上获得undefined值。此外,我正在使用回调函数,但仍然无法正常工作。我哪里错了?

$(document).ready(function() {

    function successCallback(data)
    {
        var name = data.name;
        var image = data.image;
        var link = data.link;

        var product_info = [name, image, link];
        console.log(product_info); // Correct: show my product_info array
        return product_info;
    }

    function getProductInfo(prodId, successCallback) {
        $.ajax({
            type: "POST",
            url: "getProductInfo.php",
            data: "id=" + prodId,
            dataType: "json",
            success: function(data) {
                var p_info = successCallback(data);
                console.log(p_info); // Correct: show my product_info array
                return p_info;    
            },
            error: function()
            {
                alert("Error getProductInfo()...");
            }
        });

        return p_info; // Wrong: show "undefined" value
    }

    var p_info = getProductInfo(12, successCallback);
    console.log(p_info); // Wrong: show empty value
});

0 个答案:

没有答案