每秒加载内容,无需单击按钮


Loading content every second without button click

我正在尝试创建一个页面,请求的页面在设置的间隔后刷新。

我获取了一些w3schools的基本代码,其中使用了一个按钮。但是,我希望脚本能够加载和显示内容,而无需按下按钮并在设定的时间间隔后刷新。

我不想使用Jquery,而是使用AJAX。

这会在按下按钮后将内容加载到div中的页面上,但不希望单击按钮,并在5秒钟后刷新。

<script>
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("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","content.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
setInterval(function(){loadXMLDoc();},5000);


因为你只需要调用一个方法,而不需要传递任何参数,所以使用第二个

setInterval(loadXMLDoc,5000);//preffered

更新:-

<script>
setInterval(loadXMLDoc,5000);//preffered
</script>
setInterval(function(){
    "content you want to refresh"
},5000);