ajax jquery需要一个点击更多 [英] ajax jquery needs one click more
问题描述
我有两个php文件,
- 说xyz.php
代码是: -
<?php
echo你好;
?>
2.say abc.php
代码是: -
< script type =text / javascriptsrc =jquery.js>< / script>
< script type =text / javascript>
$(document).ready(function(){
$(div.click_me)。live('click',function(){
$ .ajax({
type:POST,
data:null,
url:xyz.php,
success:function (响应){
alert(response);
}
})
} ;
});
< / script>
< div class =click_me> CLICK< / div>
只需点击divclick_me
但是问题出在这里,如果我将其代码更改为 - :
< script type =text / javascript>
$(document).ready(function(){
$(div.click_me)。live('click',function(){
res = xxx();
alert(res)
});
});
function xxx(){
$ .ajax({
type:POST,
data: null,
url:xyz.php,
success:function(response){
res = response;
}
})
return res;
}
< / script>
现在我要点击两次BOX SAYINGhello。点击一次没有发生。我真的很困惑这个愚蠢的问题。请帮助我。 Thanx很多。
Ajax是异步的。
成功
回调 strong> xxx
已返回 res
。这意味着此代码第一次运行:res = xxx();
<$ $ p>
alert(res);
res
undefined 。
另外,请阅读
var
语句。
解决方案:将回调函数传递给
xxx
:$('div.click_me')。live('click',function()
{
function alertCallback(x)
{
alert(x);
}
xxx(alertCallback);
});
function xxx(callback)
{
$ .post('xyz.php',null,function(result)
{
callback );
});
}
I have two php files,
- say xyz.php
Code is :-
<?php echo "hello"; ?>
2.say abc.php
Code is :-
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("div.click_me").live('click',function(){ $.ajax({ type:"POST", data:null, url:"xyz.php", success:function(response){ alert(response); } }) }); }); </script> <div class="click_me"> CLICK </div>
On simply clicking div "click_me", a popup box appears saying "hello" as expected.
But problem lies here if I change its code to -:
<script type="text/javascript"> $(document).ready(function(){ $("div.click_me").live('click',function(){ res=xxx(); alert(res) }); }); function xxx(){ $.ajax({ type:"POST", data:null, url:"xyz.php", success:function(response){ res=response; } }) return res; } </script>
NOW I HAVE TO CLICK TWICE TO GET THE POPUP BOX SAYING "hello". Nothing happens on clicking once. I am really confused about this stupid problem. Kindly help me . Thanx a lot.
解决方案Ajax is asynchronous.
The
success
callback setsres
toresponse
afterxxx
has returnedres
. That means the first time that this code runs:res = xxx(); alert(res);
res
isundefined
.Also, read up on the
var
statement.
Solution: pass a callback function to
xxx
:$('div.click_me').live('click',function() { function alertCallback(x) { alert(x); } xxx(alertCallback); }); function xxx(callback) { $.post('xyz.php', null, function (result) { callback(result); }); }
这篇关于ajax jquery需要一个点击更多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!