donglao9606 2016-02-02 08:11
浏览 37

AJAX动态重新加载网页

I have a ajax query which keeps reloading a div of the page in every 6 seconds.
There is a action button in that reloading div which opens a modal.
The problem is whenever page reloads the modal also refreshes. And i have to send some information through that modal but i am not able to fill up the modal as the page keeps refreshing every 6 seconds
I couldn't find a solution for that.
The files are as shown below. file1.php calls file2.php which has a table with dynamic values(i have made them static just for SO.)
P.S.: I am also looking to implement a notification system but can't figure out a way to do that. If anyone could help.
EDIT
I want the div to reload every 6 seconds but not the modal

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>
  • 写回答

1条回答 默认 最新

  • duandie5707 2016-02-02 08:38
    关注

    Okay, here is your problem:

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

    Now modal refers to your element. However, once the ajax request fetches new data, this element gets deleted and replaced by a new element with the same ID.

    What you could do is structure the data outputted from SO.php as a JSON-object, and replace only the contents of each HTML-element.

    JSON-objects generally look like this: ["This is some text!", "Even more text!"]

    If we let text.php return this data,

    As a simple example, you could request text.php through AJAX:

    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>';
        }
      }
    }
    

    And you do <div id="currentData"><p></p><p></p></div>

    The two paragraphs will be filled with the text of whatever text.php returns.

    You can also find plenty of tutorials with a simple google search :)

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?