使用jquery 的ajax,如何触发一个程序的执行,但是请求成功之后立刻执行success回调函数?


这个问题不好用语言表述,先贴一段我想实现效果的代码:

ajax:

   
  $.ajax({
  
url:'index.php',
success:function(){
alert('任务已经开始执行.....');
}
})

index.php:

   
  set_time_limit(0);
  
echo str_pad('success',1024,' ');
ob_flush();
flush();

sleep(rand(5,40)); //这里会运行一个较慢的批量处理程序,暂时用sleep模拟
file_put_contents('test.txt','1111112');
die;

当然上面的代码是实现不了的,但是能直观的看出我的意图,我希望的效果就是ajax请求index.php,index.php开始执行时,就响应ajax成功。

开始尝试过设置ajax请求的timeout:

   
  $.ajax({
  
url:'index.php',
timeout:1000,
complete:function(){
alert('任务已经开始执行.....');
}
})

这样写是没问题的,请求1秒,立刻完成,后台也不影响继续执行,但是不敢保证 请求在1内能成功发送,所以这中方案也不靠谱,不知道大家有没有更好的解决办法?

php Ajax

Olivier 12 years, 4 months ago
Gseraph answered 12 years, 4 months ago

Your Answer