2013-01-18 41 views
0

我的函數返回undefined,我不確定如何找到我正在查找的數據。

function getCustomerName(){ 

     var account = localStorage.getItem("account"); 

     $.post("http://127.0.0.1/getCustomer.php", {account:account}, function(data) { 

       alert('Inside getCustomer' + ' ' + data); 

     } ,"json"); 

} 

而getCustomer.php返回

{"nameCustomer":[{"Alarms":"0","Name":"Jane Doe"}]} 

任何幫助,將不勝感激。

+1

歡迎** **異步的奇妙世界!你需要使用回調。 – SLaks

+0

你能指點我一個這樣的例子嗎? – user1668630

+0

我已經使用回調之前的jsonp,但我不確定如何發佈/獲取使用它? – user1668630

回答

0

因爲調用是異步的,所以當getCustomerName完成執行時,數據不會從服務器返回。 getCustomerName需要採取一個回調函數:

function getCustomerName(onNameRetrieved){ 
    var account = localStorage.getItem("account"); 

    $.post("http://127.0.0.1/getCustomer.php", {account:account}, function(data) { 
     onNameRetrieved(data) //or more likely something like onNameRetrieved(data['nameCustomer'][0]['name']; 
    } ,"json"); 
} 

你再調用getCustomerName像

getCustomerName(function (name) { 
    alert('The actual name is ' + name); 
}) 
0

您的JavaScript實際上看起來不錯。你有一個回調函數。請記住,datatype參數指定從服務器返回的返回類型,而不是要發送到服務器的參數類型。確保您的服務預計將JSON作爲參數。同時驗證您檢索的account形式localStorage是否正確返回有效值。