作者TonyQ (沉默是金。)
看板Ajax
标题Re: [ js ] 有关 function return string的问题
时间Sun May 9 17:48:35 2010
※ 引述《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
1F:推 j100002ben:啊啊啊...我忘记放在Callback函数里面了.习惯写$.ajax 05/10 01:39
2F:→ j100002ben:看到$.post就忘记要放complete属性....(汗 05/10 01:40