如何分别运行多个ajax?不是一步一个脚印。 请看下面的代码。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
/*
there are 4 steps need to check with ajax,
when all steps is checked , I will finally run final_fn
I hate using $.ajax(...,function(){...}) to run ajax step after step.
any other way to let script become more simple and easy to understand?
*/
function final_fn(){
//..
}
// my original way to check 4 steps
$.ajax({
url:'a.php',
type:'POST',
data:{},
success:function(rs){
// then run ajax b.php
// then run ajax c.php
// then run ajax d.php
// then run final_fn
}
});
// now i want to do it like bellow.
$.ajax({
url:'a.php',
type:'POST',
data:{},
success:function(){}
});
$.ajax({
url:'b.php',
type:'POST',
data:{},
success:function(){}
});
// c.php
// d.php
// then final_fn()
// how to do that? final_fn must run ater all steps complte
</script>
答案 0 :(得分:2)
只要有一个计数器,每个ajax会增加它,然后检查它是否为4:
$.ajax({
url:'a.php',
type:'POST',
data:{},
success:function(){
count++;
if(count == 4) final_fn()
}
});
$.ajax({
url:'b.php',
type:'POST',
data:{},
success:function(){
count++;
if(count == 4) final_fn()
}
});
//etc.
更好的是将它放入一个函数中,如果这是你成功的唯一方法
function doIt(url) {
$.ajax({
url:url,
type:'POST',
data:{},
success:function(){
count++;
if(count == 4) final_fn()
}
});
}