2015-02-05 165 views
0

我试图读p_info函数返回从函数getproductInfo包含ajax调用,但我得到未定义的值。我使用回调函数来实现这一点,但仍然无法正常工作。我错在哪里?使用ajax和回调函数向函数传递/返回值

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

您在成功回调中声明'p_info',然后尝试在该范围之外访问它。相反,在函数的顶部声明它。 – 2015-02-05 22:23:18

+0

谢谢。正如我写给用户Neoaptt,我试图做到这一点,但仍然无法正常工作。 – KaMZaTa 2015-02-06 03:33:13

回答

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); 
+0

谢谢,但我复制并粘贴你的代码,但仍然无法正常工作。我可以在post函数中读取'temp',但不能在'return temp'之前读取,而'p_info'当然是空的。我真的可以明白问题在哪里...... – KaMZaTa 2015-02-06 03:30:10