刷新div内容,不使用Jquery,AJAX

时间:2017-09-28 02:34:27

标签: javascript ajax

如何使用普通的JS刷新AJAX插入的div的内容?这么多的例子都使用Jquery,但我试图保持轻松而不使用Jquery。到目前为止我所拥有的:

-index。 php的html页面 -livedata。带有实时数据的部分的php html -scripts。带JS的js文件

我想每10秒刷新一次页面。

var xhr = new XMLHttpRequest();                 // Create XMLHttpRequest object

xhr.onload = function() {                       // When response has loaded
  // The following conditional check will not work locally - only on a server
  if(xhr.status === 200) {                       // If server status was ok
    document.getElementById('live').innerHTML = xhr.responseText; // Update
  }
};

xhr.open('GET', 'livedata.php', true);        // Prepare the request
xhr.send(null);                                 // Send the request

这里仅供参考,是index.php

    <!doctype html>

<html>

<head>
    <title>Page Title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0">
</head>

<body>
    <section id="live">
        <p>please wait... loading content</p>
    </section>
    <script src="scripts.js"></script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

function getData() {
  var xhr = new XMLHttpRequest();                 // Create XMLHttpRequest object

  xhr.onload = function() {                       // When response has loaded
    // The following conditional check will not work locally - only on a server
    if(xhr.status === 200) {                       // If server status was ok
      document.getElementById('live').innerHTML = xhr.responseText; // Update
    }
  };

  xhr.open('GET', 'livedata.php', true);        // Prepare the request
  xhr.send(null);                                 // Send the request
}

setInterval(getData, 1000*10);