duanfu1873 2017-06-02 07:17
浏览 51
已采纳

如何在未完成时从ajax触发的PHP调用获取更新?

Is there a way to get updates from a PHP process while it's not finished and it has been called by ajax? By updates i mean flushed output from the PHP script.

  1. var proc;
  2. $('#start').click(function () {
  3. proc = $.ajax({
  4. type: 'POST',
  5. url: 'execute.php',
  6. // getData function that will get me updated data
  7. getData: function (update){
  8. alert(update);
  9. }
  10. });
  11. });

UPDATE: Lets say we want to get that echo before this ends.

execute.php

  1. <?php
  2. $progress = 0;
  3. while(1){
  4. $progress++;
  5. echo $progress;
  6. flush();
  7. sleep(5);
  8. if($progress == 100){
  9. break;
  10. }
  11. }
  12. ?>

FINAL:

myScript.js

  1. var strongcalcs;
  2. var source;
  3. $('#start').click(function () {
  4. strongcalcs = $.ajax({
  5. type: 'POST',
  6. url: 'execute.php',
  7. beforeSend: function () {
  8. rpm_percent();
  9. },
  10. success: function(result){
  11. source.close();
  12. },
  13. complete: function () {
  14. source.close();
  15. },
  16. error: function () {
  17. source.close();
  18. }
  19. });
  20. });
  21. function rpm_percent() {
  22. source = new EventSource("execute.php");
  23. if(typeof(EventSource) !== "undefined") {
  24. source.onmessage = function(event) {
  25. console.log(event.data);
  26. };
  27. } else {
  28. alert("nono");
  29. }
  30. }

execute.php

  1. <?php
  2. $coco = 0;
  3. function sendMsg($msg, &$coco) {
  4. echo "id: " . $coco . "
  5. ";
  6. echo "data: " . $msg;
  7. echo "
  8. ";
  9. echo "
  10. ";
  11. ob_flush();
  12. flush();
  13. $coco++;
  14. }
  15. header("Content-Type: text/event-stream");
  16. header("Cache-Control: no-cache");
  17. $progress = 0;
  18. while(1){
  19. sendMsg($progress++, $coco);
  20. ob_flush();
  21. flush();
  22. sleep(5);
  23. if($progress == 100){
  24. break;
  25. }
  26. }
  27. ?>

展开全部

  • 写回答

2条回答 默认 最新

  • duanpao4172 2017-06-02 07:22
    关注

    I've in the past used Server Sent Events for this (https://www.w3schools.com/html/html5_serversentevents.asp). Internet Explorer is not supported out of the box, but there are polyfills that can solve the issue.

    I think Websockets do something similar but don't have experience with those myself.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部