2013-01-18 40 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是否正确返回有效值。