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

前端 未结 3 1659
孤城傲影
孤城傲影 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:53

    Honestly I'm having a hard time with the code you posted, mostly because I don't understand the JSON example. If you are going to be storing flat HTML as the JSON values, it makes more sense to just $.ajax the HTML into the DOM rather than JSON encoding, parsing and inserting. That being said, I am going to assume that the JSON was not a realistic example and that it will take more of the form:

    { class_name: "Class 1", description: "Blah Blah Blah" }

    With that assumption in mind, this well-documented but untested example should point you in the right direction. Essentially, I do the following:

    • Define an HTML template
    • Create a simple templating function to transpose the JSON values into the HTML template
    • Setup an interval to poll the server for new data using setInterval calling a function which passes a timestamp of the last time we requested to your JSON generating server-side script using getJSON

    Here is my example, please let me know if you have any questions.

    
    

    Also, just to put a bow on this, if you are just return HTML from the server, you can (for the most part) simply replace $.getJSON with $.get, forgo all of the template rendering on the client-side and just append the response to the DOM

    (function(){
        var SECONDS_TO_POLL = 3
        ,   $parent_node = $('#node-to-append-to')
        ,   last_timestamp = null // this will be a timestamp passed to the server
    
        // this is our polling function, will retrieve the HTML from the server and render to the DOM
        var poller = function(){
            // load the HTML pass a GET var telling the server what timestamp to query from (e.g. WHERE data.timestamp > last_timestamp)
            $.get('/path/to/server?last_retrieved='+last_timestamp, function(html){
                // append the result to the parent DOM node
                $parent_node.append(html);
            })
            // get a current timestamp so that we can limit the server results to those 
            last_timestamp = new Date().getTime();
        }
    
        // retrieve new results every N seconds
        setInterval(poller, SECONDS_TO_POLL*1000);
    })()
    

提交回复
热议问题