2015-02-05 197 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