使用ajax和回调函数向/从函数传递/返回值

时间:2015-02-05 22:21:15

标签: javascript jquery ajax

我正在尝试读取包含ajax调用的函数p_info返回的getproductInfo数组,但是我得到了未定义的值。我正在使用回调函数来实现这一点,但仍然无法正常工作。我哪里错了?

$(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: shows 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: shows my product_info array
                return p_info;    
            },
            error: function()
            {
                alert("Error getProductInfo()...");
            }
        });

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

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

1 个答案:

答案 0 :(得分:0)

代码应该说明一切。但基本上,你不能在函数内返回一个高级函数。您必须设置一个变量,用于在提交ajax后返回。

//This makes the p_info global scope. So entire DOM (all functions) can use it.
var p_info = '';

//same as you did before
function successCallback(data) {
    var name = data.name;
    var image = data.image;
    var link = data.link;

    var product_info = [name, image, link];
    return product_info;
}

//This takes prodID and returns the data.
function getProductInfo(prodId) {
    //sets up the link with the data allready in it.
    var link = 'getProductInfo.php?id=' + prodId;
    //creates a temp variable above the scope of the ajax
    var temp = '';
    //uses shorthand ajax call
    $.post(link, function (data) {
        //sets the temp variable to the data
        temp = successCallback(data);
    });
    //returns the data outside the scope of the .post
    return temp;
}

//calls on initiates.
var p_info = getProductInfo(12);
console.log(p_info);