有這么一個場景:服務端處理數據,響應比較慢,為了不讓用戶體會到網頁沒有反應,服務端需要把處理的每一步操作返回給前端,前端實時進行打印。
1.ajax 輪詢
<script> setInterval("test()",2000); function test() { $.ajax({ url: '/new_window_url/', async:false, type: 'get', success: function (data) { console.log(data) } }) } </script>
2.EventSource 長鏈接
前端代碼:
<!doctype html> <html lang="en"> <head> <title>Sse測試文檔</title> <meta charset="utf-8"> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdn.bootcss.com/event-source-polyfill/0.0.9/eventsource.min.js"></script> </head> <body> <div></div> </body> </html> <script> var source = new EventSource('http://127.0.0.1:8080/event/query'); //只要和服務器連接,就會觸發open事件 source.addEventListener("open",function(){ console.log("和服務器建立連接"); }); //處理服務器響應報文中的load事件 source.addEventListener("load",function(e){ console.log("服務器發送給客戶端的數據為:" + e.data); }); //如果服務器響應報文中沒有指明事件,默認觸發message事件 source.addEventListener("message",function(e){ console.log("服務器發送給客戶端的數據為:" + e.data); }); //發生錯誤,則會觸發error事件 source.addEventListener("error",function(e){ console.log("服務器發送給客戶端的數據為:" + e.data); }); </script>
服務端代碼:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; @SpringBootApplication @RestController @RequestMapping("event") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @ResponseBody @CrossOrigin @RequestMapping(value="query") public void query(HttpServletResponse response) throws IOException, InterruptedException { response.setHeader("Content-Type","text/event-stream"); response.setContentType("text/event-stream;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("data:Hello World"); out.println("event:load"); out.println("id:140312"); out.println(); out.flush(); out.close(); } }