【问题标题】:Jquery AJAX live output?Jquery AJAX 实时输出?
【发布时间】:2017-06-30 14:16:34
【问题描述】:

我正在尝试从 AJAX 请求中获取一些实时输出。

这是我正在使用的代码:

$.ajax({ type: "GET",   
     url: "test.php?delete=students",   
     async: true,
     success : function(data) {
         console.log(data)
     }
    });

当我的网页上的链接触发时,会显示一个旋转动画以显示正在发生的事情。我还想在 div 中显示 test.php 运行时的输出。

test.php 有一个简单的循环,它遍历所有学生并将其删除,然后echo "$student removed";

当从命令行运行时,会显示删除,当通过 AJAX 运行时,我只得到动画而不是输出。

我不知道如何获得它,我已经尝试了几个插件,但都没有成功。我也尝试过使用XMLHttpRequestresponseText,但我不确定如何正确使用它。

理想情况下,我希望每个删除都显示在 #status div 中。

任何人都可以建议如何做到这一点?

更新

 progress : function(data) {
    console.log(data);
 },

我已经添加了上面的内容并移动我在控制台中得到了一些输出。 ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 44, total: 0, type: "progress"…}

扩展我可以看到包含我所追求的数据的响应文本。 我如何得到它,以便我可以将它附加到 div

【问题讨论】:

  • 如果我是正确的,AJAX 中的success 只有在 php 关闭 HTTP 连接后才会调用回调,我自己也很困惑,所以希望得到更多响应。
  • 嗨。 success 确实返回正确,我正在尝试获取正在发生的输出。刚要更新我原来的帖子
  • 我的意思是,你不能流式传输 tets.php 的进度,浏览器不会读取任何内容,直到 php 连接关闭
  • 我可以取得一些进展,我不确定如何获得文本。
  • html5rocks.com/en/tutorials/websockets/basics,使用这个。应该有帮助。另外,我很抱歉。我想我误解了你的问题。

标签: php jquery ajax xmlhttprequest


【解决方案1】:

您可以尝试使用服务器发送的事件:https://html.spec.whatwg.org/multipage/comms.html#server-sent-events

客户端代码会很简单:

var sse = new EventSource('test.php?delete=students');
sse.addEventListener('message', function(e) {
  console.log(e.data);
}, false);

在您的 test.php 中,代码将如下所示:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

for ($i = 0; $i < ob_get_level(); $i++) {//for each open buffer
  ob_end_flush();//close it
}

ob_implicit_flush(1);//turn implicit flush on

//now goes what you called "loops through all students and deletes them"
while(1) {
  /*here you post your code that deletes your student*/
  $data = "$student removed";//message to send to client confirming deleting of particular student
  echo "data: ".$data . PHP_EOL;//here you send data to client, it will receive it and handle inside 'message' event handler
  echo PHP_EOL;//need this just to fulfill the SSE standard
  sleep(1);//use if need to insert pause between sending new portion of data (better use it to keep your browser safe from too much of messages per second)
}

完成删除学生后不要忘记打破循环=)

【讨论】:

  • 您好,谢谢您,我将在今天晚些时候尝试 - 超时会有任何问题吗?如果 test.php 需要 x 分钟才能完成会导致任何问题吗?它可能正在删除或更新 100,000 个条目。
  • 如果连接断开,EventSource 会尝试自动重新打开它。所以你只需要确保你的服务器端逻辑在远程客户端断开连接时停止执行(检查你的 'ignore_user_abort' 在 php.ini 中是否设置为'off',如果它有任何问题)并从上一个操作继续重新打开连接后。如果出现问题,您还可以在客户端使用“错误”事件处理程序来通知客户端。检查我的答案中的链接以获取有关它的更多信息。
  • 抱歉,我只是设法回到这个问题。我收到错误 EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
  • 确保您已正确发送标头
猜你喜欢
  • 1970-01-01
  • 2016-01-01
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
相关资源
最近更新 更多