Autorefreshing/updating table using jQuery ajax by either using json or html files

前端 未结 3 1652
孤城傲影
孤城傲影 2020-12-15 04:25

So @SOF,

I\'ve been trying to make my webpage of school grades, results, projected grades... etc have an auto update feature so that the data on the page refreshes w

3条回答
  •  半阙折子戏
    2020-12-15 04:49

    The best way to solve your problem is to use a binding library such as knockout. With it you separete your data and your view and only have to worry how you update the data, the view will get updated automatically. This is what it seems you are currently struggeling with.

    That's why I made small sample generating a list and updating the data by constantly polling to it (using a fake service which always returns the same data which changes randomly).

    Here is the example I did by using knockout: Please take a look at the knockout documention page: http://knockoutjs.com/documentation/introduction.html

    HTML: Define a simple table with header and content

    http://jsfiddle.net/yBat5/#fork
                

    Classes

    Childs

    JavaScript:

    $(function () {
       // define a ViewModel for your data
        function ViewModel() {
            this.Classes = ko.observableArray([{
                "Class": "test",
                    "Child": "Max"
            }, {
                "Class": "test2",
                    "Child": "Walter"
            }]);
        }
    
        var vm = new ViewModel(),
            dummyData = [];
    
        // create a lot of dummy data sets
        for (var i = 0; i < 1000; i++) {
            dummyData.push({
                "Class": "test " + i,
                    "Child": "Child" + i
            })
        }
    
        // constantly poll for new data
        // JS fiddle implements a simple echo service, which we can use
        // to simulate data changes we change a rendon number
        function poll() {
            $.ajax({
                "url": "\/echo\/json\/",
                    "type": "POST",
                    "data": {
                    "json": JSON.stringify(dummyData),
                        "deley": 3
                },
                    "success": function (data) {
                    vm.Classes(data);
    
                    // poll again (3 seconds so we see how fast the update is)
                    setTimeout(poll, 300);
    
                        // change a random entry to see that data changes
                    var randomnumber=Math.floor(Math.random()*1000);
                        dummyData[randomnumber].Child = "Child"  +randomnumber +" changed"
                }
            });
        }
    
        poll();
    
        // apply it to the page, knocout now does the binding for you
        ko.applyBindings(vm);
    });
    

    Fiddle: http://jsfiddle.net/yBat5/3/

提交回复
热议问题