How to periodically update data without refreshing the page?

I am trying to create a web application to monitor system activity, and I am using Flask as my CMS. In particular, I am stuck trying to periodically update system information without refreshing the page. Now I am testing a web application, getting local information as a percentage.

I created a route called "/ refresh" and added local information to the JSON format:

@app.route('/refresh')
    def refreshData():
        systemInfo = {'cpuload': si.getCPU(), 'memload': si.getMEM(), 'diskload': si.getDiskSpace()}
        return jsonify(systemInfo)

The data is as follows:

{
  "cpuload": 4.3, 
  "diskload": 0.7, 
  "memload": 27.8
}

I am currently using Flask variables to display information in my template, but I would like to access the JSON data in a script in HTML and set it to an HTML element and have such an update so often, I tried using knockout, but I couldn’t make it work. My template looks like this:

<ul id='sysInfo'>
    <li>Hostname: {{ sysInfo[0] }}</li>
    <li>CPU Core Count: {{ sysInfo[1] }}</li>
    <script type='text/javascript' src="http://code.jquery.com/jquery.min.js"></script>
    <script type='text/javascript' src="http://knockoutjs.com/downloads/knockout-3.1.0.js">
        function update() {
            $.getJSON('/refresh', function(data) {
                $('#cpu').html(data[cpuload]);
                window.setTimeout(update, 5000);
            });
        }
    </script>
    <li>
        <div id="progress">
            <span id="percent">CPU usage: <div id="cpu"></div>%</span>
            <div style ='height: 20px; background-color: green; width: {{ cpuLoad }}%;'></div>
        </div>
        </li>

, script HTML , getJSON (, ), HTML.

+4
1

jsfiddle, , . , :

Full Bore, : http://jsfiddle.net/FgbKd/15/

Bare Bones, Just Works: http://jsfiddle.net/FgbKd/1/

jsfiddle, .

END UPDATE

, , viewmodel, , .

function myViewModel (data) {
    data = data || {}; var self = this;
    self = ko.mapping.fromJS(data);
  return self;
}

. , - json . .

. :

var myServerData;
$(document).ready(function(){
    myServerData = new myViewModel(data_json_received);    //
    ko.applyBindings(MyObject);     //myServerDataapplies the bindings found in HTML
});

. myServerData, , . , , , . MyObject.cpuload .

, myServerData, AJAX viewmodel , :

ko.mapping.fromJS(new_json_data, {}, myServerData);

, :

$.ajax({ 
  ....
  success : function(data){
     ko.mapping.fromJS(data, {}, myServerData);   //refreshes it
  }
});

, . MyServerData json, HTML , :

<SPAN data-bind="text: cpuload"></SPAN>
<SPAN data-bind="text: diskload"></SPAN>
<SPAN data-bind="text: memload"></SPAN>

, , JS , , , mapping.fromJS , .

+5

Source: https://habr.com/ru/post/1546342/


All Articles