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

Passing/returning value to/from a function using ajax and callback function

本文关键字:函数 返回值 ajax 回调 使用      更新时间:2023-09-26

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

$(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
});

代码应该不言自明。但基本上,你不能在函数中返回一个更高级别的函数。您必须设置一个变量,以便在提交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);