Re: [ js ] 有關 function return string的問題
※ 引述《ot32em (reverse(wasefo);)》之銘言:
: 標題: [ js ] 有關 function return string的問題
: 時間: Sat May 8 13:44:55 2010
:
: $(document).ready(function(){
: ...
:
: function accountCheck(a){
: if( a.length < 3 ) return 'short';
: if( a.length > 11) return 'long';
: $.post('fetch.php', { "type":"ncuaccount", "email": 'someemail'
: , "week": '30'}
: , function(data){ alert(data);return data; } );
: }
: 綠色的可以回傳資料
: 可是在下面我alert result時
: 卻是undefined or 空字串
: 這會是因為.post要等 然後 function accoutnCheck(a) 等不及就return的關係嗎?
:
: $('#register_submit').click(function(){
: var acc = $('#register_account').val();
: var result = "";
: result = accountCheck( acc );
: alert(result);
:
: ...
: });
:
: --
: ※ 發信站: 批踢踢實業坊(ptt.cc)
: ◆ From: 61.62.77.187
: → grence:ajax就是非同步啊.... 05/08 16:26
: → j100002ben:你用匿名函式return給jQuery的post方法他要回傳什麼? 05/08 22:24
: → j100002ben:var一個外部(靜態)變數取存資料吧 05/08 22:25
: → j100002ben:TO:1F,樓主的問題和非同步沒有關係..... 05/08 22:25
: → j100002ben:function accountCheck(a){ 05/08 22:29
: → j100002ben: if( a.length < 3 ) return 'short'; 05/08 22:29
: → j100002ben: if( a.length > 11) return 'long'; 05/08 22:29
: → j100002ben: var return_data; 05/08 22:29
: → j100002ben:$.post('fetch.php', { "type":"ncuaccount", "email": 05/08 22:29
: → j100002ben: 'someemail', "week": '30'} 05/08 22:30
: → j100002ben:, function(data){ alert(data);return_data=data;}); 05/08 22:30
: → j100002ben: return return_data;} 05/08 22:31
當然 accountCheck 沒有 return 值是個問題,不過非同步也有關系,
不過非同步在你修正之後的sample就有影響了;
因為預設是非同步的話,你return_data還沒取得資料前,
accountCheck 很有可能已經 return了.
一般來講得作法就是把之後的流程寫成 callback ,
透過 accountCheck在 post 回來之後執行。
: → ot32em:我有用一個外部存過 好像也是GG 我在$.post上有令個var r; 05/09 17:26
: → ot32em:後來也是UNDEFINED 05/09 17:26
因為非同步造成的影響版上沒有三篇也有五篇,
有興趣請往前爬爬文就是...
--
I am a person, and I am always thinking .
Thinking in love , Thinking in life ,
Thinking in why , Thinking in worth.
I can't believe any of what ,
I am just thinking then thinking ,
but worst of all , most of mine is thinking not actioning...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.137.57.162
推
05/10 01:39, , 1F
05/10 01:39, 1F
→
05/10 01:40, , 2F
05/10 01:40, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章