如何使用ajax连续刷新多个div部分?
AJAX
<script type="text/javascript">
<%
for(Server i : svr )
{
%>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("refresh").innerHTML=xmlhttp.responseText;
document.getElementById(<%=i.getName()%>).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost:8080/RefreshStatus/<%=i.getId()%>", true);
xmlhttp.send();
}
<%
}
%>
//setInterval(loadXMLDoc, 5000 );
setInterval(loadXMLDoc, 500 );
</script>
REST的HTML
</head>
<body>
Status 1 <div id="refresh">whatever is in here gets changed</div>
Status 2 <div id="refresh">whatever is in here gets changed</div>
Status 3 <div id="refresh">whatever is in here gets changed</div>
答案 0 :(得分:1)
首先,为页面上的每个元素使用唯一ID。你不能有重复,否则事情就会开始破坏。如果可以的话,让他们共享相同的CSS类:
Status 1 <div class="refresh">whatever is in here gets changed</div>
Status 2 <div class="refresh">whatever is in here gets changed</div>
Status 3 <div class="refresh">whatever is in here gets changed</div>
如果你可以使用jQuery,那就试试这个:
$('.refresh').html('New status OK!');
如果你不能使用jQuery,那么你可以get elements by class name遍历所有这些并一次设置一个innerHTML属性。
element.innerHTML = 'New status OK!';