【问题标题】:Refresh div content, without Jquery, AJAX刷新div内容,不用Jquery、AJAX
【发布时间】:2017-09-28 02:34:27
【问题描述】:

如何使用纯 JS 来刷新 AJAX 插入的 div 的内容?如此多的示例使用 Jquery,但我试图保持轻松而不使用 Jquery。到目前为止我所拥有的:

-索引。 php html页面 -实时数据。带有实时数据的部分的 php html -脚本。 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>

【问题讨论】:

  • 您的代码是否有效 - 看起来应该更新一次……每 10 秒,使用 setInterval
  • 看起来不错。检查浏览器开发者工具中的网络选项卡,查看向 livedata.php 发送请求时返回的内容。

标签: javascript ajax


【解决方案1】:

你可以试试这个:

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

【讨论】:

  • 当我第一次加载页面时,我必须等待 10 秒才能显示数据,然后它开始每 10 秒刷新一次?我希望立即加载数据然后开始刷新。有人建议怎么做吗?
  • 在脚本中添加一行很容易。 window.onload = getData();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 2023-04-03
  • 1970-01-01
  • 2011-06-03
  • 2012-09-16
相关资源
最近更新 更多