假设您想在您的网页上显示一些 live feed 内容(比如 livefeed.txt)而不进行任何页面刷新,那么以下 简化 示例适合您。
在下面的 html 文件中,live data 会在 id "liveData" 的 div 元素上更新>
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
autoUpdate.js 使用 XMLHttpRequest 对象读取实时数据并每 1 秒更新一次 html div 元素。为了更好地理解,我在大部分代码上都给出了 cmets。
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
出于测试目的:只需在 livefeed.txt 中编写一些内容 - 您将在 index.html 中获得相同的更新而无需任何刷新。
livefeed.txt
Hello
World
blah..
blah..
注意:您需要在web服务器(例如:http://localhost:1234/index.html)上运行上述代码,而不是作为客户端html文件(例如:file:///C:/index.html)。