how to update the page without refresh

后端 未结 4 1454
旧巷少年郎
旧巷少年郎 2021-01-17 04:22

In Gmail when a new email is received, the page automaticly show the mail without refreshing, how this can be done?

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 04:54

    You could send AJAX requests at regular intervals using the window.setInterval function to the server checking if there are updates:

    window.setInterval(function() {
        // this code will execute on every 5s
        // so we could send an AJAX request to verify if we
        // have new data. Example with jQuery:
        $.getJSON('/foo', { }, function(result) {
            if (result.newItems) {
                // TODO: update the DOM with the items
            }
        });
    }, 5000);
    

    Another possibility is to use the HTLM5 WebSocket API which allows the server to push updates to the client instead of the client polling for updates.

提交回复
热议问题