我正在尝试从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运行时,我只获取动画而不是输出。
我不知道怎么做到这一点,我尝试了几个插件并取得了很大的成功。我还尝试使用XMLHttpRequest
和responseText
,但我不确定如何正确使用它。
理想情况下,我希望每个删除都显示在#status
div。
任何人都可以建议如何做到这一点吗?
更新
progress : function(data) {
console.log(data);
},
我添加了以上内容并移动我在控制台中获得了一些输出。
ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 44, total: 0, type: "progress"…}
扩展我可以看到包含我所追求的数据的responsetext。
我该如何获得,以便将其附加到div
?
答案 0 :(得分:0)
您可以尝试使用服务器发送的事件: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)
}
完成删除学生后不要忘记打破循环=)