简体   繁体   English

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

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

I'm trying to read p_info array returned from the function getproductInfo containing a ajax call but I'm getting undefined value. 我正在尝试读取从包含ajax调用的getproductInfo函数返回的p_info数组,但是得到的是不确定的值。 I'm using a callback function to achieve this but still doesn't work. 我正在使用回调函数来实现此目的,但仍然无法正常工作。 Where am I wrong? 我哪里错了?

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

The code should speak for itself. 该代码应该说明一切。 But basically, you cant return an upper-level function inside a function. 但基本上,您不能在函数内部返回上级函数。 You must set a variable to be used to return after the ajax is submitted. 提交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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM