2015-02-05 2 views
0

getproductInfo에서 반환 된 배열 p_info 배열을 읽으려고 시도 중이지만 정의되지 않은 값이 나타납니다. 이를 달성하기 위해 콜백 함수를 사용하고 있지만 여전히 작동하지 않습니다. 내가 어디서 잘못한거야?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'를 선언 한 다음 해당 범위 밖에서 액세스하려고합니다. 대신 함수의 맨 위에 선언하십시오. –

+0

감사합니다. Neoaptt 사용자에게 쓴 것처럼이 작업을 시도했지만 여전히 작동하지 않습니다. – KaMZaTa

답변

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

관련 문제