簡體   English   中英

Jquery AJAX實時輸出?

[英]Jquery AJAX live output?

我正在嘗試從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中。

任何人都可以建議如何做到這一點?

UPDATE

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

我添加了上面的內容並移動我在控制台中獲得一些輸出。 ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 44, total: 0, type: "progress"…}

擴展我可以看到包含我之后的數據的responsetext。 我該怎么做才能將它附加到div

您可以嘗試使用服務器發送的事件: 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)
}

完成刪除學生后不要忘記打破你的循環=)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM