【问题标题】:AJAX to dynamically reload webpageAJAX 动态重新加载网页
【发布时间】:2016-02-02 08:11:46
【问题描述】:

我有一个 ajax 查询,它每 6 秒不断重新加载页面的 div。
有一个 操作按钮在打开 modal 的重新加载 div 中。
问题是,每当页面重新加载时,modal 也会刷新。我必须通过该模式发送一些信息,但我无法填写模式,因为 页面每 6 秒刷新一次
我找不到解决方案。
文件如下所示。 file1.php 调用具有动态值的表的 file2.php(我已将它们设为静态,仅用于 SO。)
P.S.: 我也在寻求实现通知系统,但不能想办法做到这一点。如果有人可以提供帮助。
编辑
我希望 div 每 6 秒重新加载一次,而不是模式

file1. php

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
   <title>AJAX Example</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <script type="text/javascript" src="reloader.js"></script>
</head>

<body onload="reloadData()">
<p> HELLO There!</p>
   <div id="currentData" align="center">
      <p>Loading Data...</p>
   </div>
</body>
<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>
<script>
var req;

function reloadData()
{
   var now = new Date();
   url = 'SO.php?' + now.getTime();

   try {
      req = new XMLHttpRequest();
   } catch (e) {
      try {
         req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (oc) {
            alert("No AJAX Support");
            return;
         }
      }
   }

   req.onreadystatechange = processReqChange;
   req.open("GET", url, true);
   req.send(null);
}

function processReqChange()
{
   // If req shows "complete"
   if (req.readyState == 4)
   {
      dataDiv = document.getElementById('currentData');

      // If "OK"
      if (req.status == 200)
      {
         // Set current data text
         dataDiv.innerHTML = req.responseText;

         // Start new timer (1 min)
         timeoutID = setTimeout('reloadData()', 6000);
      }
      else
      {
         // Flag error
         dataDiv.innerHTML = '<p>There was a problem retrieving data: ' + req.statusText + '</p>';
      }
   }
}
</script>
</html>

SO.php

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
</style>
</head>
<body>

<table>
<tr>
<th>Firstname</th>
<th>Mobile</th>
<th>Email</th>
<th>Hometown</th>
<th>Action</th>
</tr>
    <tr>
    <td>Irshad</td>
    <td>9876543210</td>
    <td>abc@example.com</td>
    <td>Earth</td>
    <td><button id="myBtn" data-toggle="modal" data-target=".modal">Action</button></td>
    </tr>
</table>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <p>Some text in the Modal..</p>
  </div>

</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>
</body>
</html>

【问题讨论】:

  • 它每 6 秒重新加载一次,因为你告诉它:setTimeout('reloadData()', 6000);,setTimeout 第二个参数以毫秒为单位,如果你想要一分钟,它会是 60000
  • 仅将数据加载到网站中,而不是 HTML。你最好请求 JSON 而不是 HTML,并用新数据动态更新你的 div。
  • @TRGWII 我该怎么做?我对 JSON 没有任何想法
  • 您需要修改 SO.php,使其返回 JSON,而不是 HTML。一般来说,将数据与视图分开会更好。
  • @TRGWII 有什么方法可以让我达到同样的效果吗?教程或任何可以帮助我的东西。

标签: javascript php jquery ajax notifications


【解决方案1】:

好的,这是你的问题:

var modal = document.getElementById('myModal');

现在modal 指代您的元素。 但是,一旦 ajax 请求获取新数据,该元素就会被删除并替换为具有相同 ID 的新元素。

您可以做的是将SO.php 输出的数据构造为 JSON 对象,并仅替换每个 HTML 元素的内容。

JSON 对象通常如下所示: ["This is some text!", "Even more text!"]

如果我们让 text.php 返回这个数据,

举个简单的例子,你可以通过 AJAX 请求 text.php:

function reloadData()
{
  url = 'text.php?' + Date.now();
  try {
    req = new XMLHttpRequest();
  } catch (e) {
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (oc) {
        alert("No AJAX Support");
        return;
      }
    }
  }
  req.onreadystatechange = processReqChange;
  req.open("GET", url, true);
  req.send(null);
}

function processReqChange()
{
  if (req.readyState == 4)
  {
    dataDiv = document.getElementById('currentData');
    if (req.status == 200)
    {
      obj = JSON.parse(req.responseText); // This now represents the JSON object.
      for(var i = 0; i < obj.length; i++){
        dataDiv.getElementsByTagName('p')[i] = obj[i];
      } 
       timeoutID = setTimeout('reloadData()', 6000);
    }
    else
    {
      dataDiv.innerHTML = '<p>There was a problem retrieving data: ' + req.statusText + '</p>';
    }
  }
}

而你呢&lt;div id="currentData"&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;/div&gt;

这两个段落将填充任何 text.php 返回的文本。

您还可以通过a simple google search 找到大量教程:)

【讨论】:

  • 如何使用 JSON 添加 SO.php 的数据?我提到了SO.php,你可以看看:P
  • 你需要让 SO.php 输出 JSON 而不是 HTML。
猜你喜欢
  • 2015-08-25
  • 2021-07-19
  • 2019-09-07
  • 1970-01-01
  • 2015-08-29
  • 2018-09-04
  • 2017-05-10
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多