How to achieve real-time data refresh the page?

HowNet new sources of business, the original title: succinctly page refresh data in real time to achieve

This article is only techniques and simple example, the back-end framework Django, whether specific business logic and reasonable can not control, the bottom is the work needs to be achieved

Automated script to run three job status:

1 and did not execute 2, 3 successful execution, failed execution

Task status in real time to show the front page, it is necessary from time to time request status data field in the database is webtask_stu, and return to the front display

Knowledge maps, real-time data refresh achieve succinctly page

Two ideas:

1, the front end of poll request every time, establish a connection, a front-end data returned by the backend

Specific implementation: setting a timer, every 5s backend data request, data is returned to render the front end rear end

2, only the front end of a request to establish a connection, the rear end can continue to actively push the data to the front end

Specific implementation: front end to the rear end is established by way of socket connector, the rear end of polling the database data, the initiative to push forward end, this advantage is obvious, it can reduce the number of network requests

A mode: Ajax timer request:

1, the front end of the setInterval set the timer, the timer function which pass requests and time ajax

function get_stu_list(){

 param = {}; $.post("/web/webtask_stu/",param,function(data){    var webtask_tu_list = data.webtask_stu;    console.log(webtask_tu_list);    var tr = $("tbody tr");   $.each(tr,function (i,ele) {      $(ele).find("td:eq(4)").text(webtask_tu_list[i])   });  });};setInterval(get_stu_list,5000);

The back-end is also very simple, you can return query data to JSonResponse

@csrf_exempt

def webtask_stu(request):  webtasks = Webtask.objects.all()  webtask_stu_list = []   for webtask in webtasks:    webtask_stu_list.append(webtask.webtask_stu)    dit = {'webtask_stu': webtask_stu_list}    print(webtask_stu_list)   return JsonResponse(dit)

Second way, websocket

FIG follows effect, push the front end to the rear end of the continuous data, the output of the front end of the console Demo

Knowledge maps, real-time data refresh achieve succinctly page

1, the front end portion configured socket connection object websocket protocol is a protocol, not http protocol, beginning with the front ws

2, windows.loaction.host can get the domain name (including the port)

3, the following method is mainly used, you can see the specific comments

socket.onopen: a successful connection

socket.onmessage: successfully obtained data returned by the backend, rendering state data returned by the backend jquery achieved by refreshing effect

socket.onclose: connection failure

4, back to the rear end of the string, will need to turn the front end of the object JSON.parse

var socket = new WebSocket("ws:" + window.location.host + "/web/webtask_stu/");

= socket.onopen  function ( ) {     the console.log ( 'a WebSocket Open'); // successful connection socket.send Websocket ( 'adasdasda ....'); // send data to the server}; socket.onmessage =  function ( E) {     // the console.log ( 'Message:' + e.data); // print data returned from the server      // the console.log (typeof (e.data));      the console.log ( the JSON.parse (e.data));      // the console.log (typeof (the JSON.parse (e.data)));      var = webtask_stu_list  the JSON.parse (e.data);      var TR = $ ( "tbody TR"); $ .each (TR, function ( I, ELE) {$ (ELE) .find ( . "TD: EQ (. 4)") text (webtask_stu_list [ "webtask_stu"] [I])});}; Socket.onclose=function(E) {   the console.log (E); the Socket.close ();  // close the TCP connection};

Django back-end part:

1, django installation program then dwebsocket, pip install dwebsocket, and introduced in the code

from dwebsocket.decorators import accept_websocket

2, plus decorator @accept_websocket, the request receiving socket

3, if request.is_websocket, websocket determine whether the request is then executed our back-end data from a database query function

4, to achieve data transmission every 5 seconds while the distal loop and through time.sleep

4, request.websocket.send (json data) to return data to the front end, because it is json data format, the front end JSON.parse turn to use the above objects,

@accept_websocket

def webtask_stu(request):    if request.is_websocket():      while 1:       webtasks = Webtask.objects.all()       webtask_stu_list = []        for webtask in webtasks:         webtask_stu_list.append(webtask.webtask_stu)         dit = {'webtask_stu': webtask_stu_list}        time.sleep(5)       request.websocket.send(json.dumps(dit))

Roughly two ideas as to realize there are other more advanced api socket, are interested can look at online learning.

Guess you like

Origin www.cnblogs.com/xinzhihao/p/11010443.html
Recommended