简体   繁体   English

刷新div内容,无需Jquery,AJAX

[英]Refresh div content, without Jquery, AJAX

How do you use just plain JS to refresh the content of the an AJAX inserted div? 您如何仅使用普通JS刷新AJAX插入的div的内容? So many examples use Jquery but I'm trying to stay light and not use Jquery. 如此多的示例使用Jquery,但我试图保持简洁而不使用Jquery。 What I have so far: 到目前为止,我有:

-index. -指数。 php the html page -livedata. php html页面-livedata。 php html of the section with the live data -scripts. 带有实时数据-scripts部分的php html。 js file with the JS JS的js文件

I want to refresh page every 10 seconds. 我想每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

Just for reference here is index.php 仅供参考,这里是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>

You can try this: 您可以尝试以下方法:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM