AJAX显示数据动态刷新,面试题,俺不会AJAX,请各位帮忙解答一下 - Web 开发 / Ajax
做一个AJAX显示数据动态刷新的例子,后台可以用随机数产生数据,前台动态显示,1秒1次。
------解决方案--------------------一个Timer+微软的Ajax UpdatePanel就可以实现了
------解决方案--------------------setTimeout/setInterval轮询动态页
------解决方案--------------------javascript
1.1秒更新
var timerID = 0;
window.onload = function(){
GetRecentInfo();
timerID = window.setInterval("GetRecentInfo()",1000 );
}
2.创建提出请求
function GetRecentInfo()
{
try{
XMLhttpObject = new XMLHttpRequest();
}catch(e){
try{
XMLhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
XMLhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
alert("XMLhttpObject error");
}
}
}
if(XMLhttpObject) {
XMLhttpObject .onreadystatechange = DisplayInfo;入返回时处理函数名)
XMLhttpObject .open("POST", "/servletname(写入servlet的配置名称)",true)
XMLhttpObject .setRequestHeader("content-type","application/x-www-form-urlencoded;charset=UTF-8");
XMLhttpObject.send("pageid=jspname(写入response返回的叶面名);
}
}
3.表示信息
function DisplayInfo()
{
if((XMLhttpObject.readyState == 4 ) && (XMLhttpObject.status == 200)) {
var csvdata = XMLhttpObject.responseText;
var LF = String.fromCharCode(10);
var lineData = csvdata.split(LF);
if( lineData.length > 0 ) {
document.getElementById("info").innerText = lineData[0];
}else{
document.getElementById("info").innerText = "取得失败";
}
}
}
------解决方案--------------------