简体   繁体   English

停止在PHP AJAX MySQL中重复div内容

[英]Stop repeating div content in PHP AJAX MySQL

I am trying to retrieve the data dynamically from MySQL database into web page using AJAX technique but the div content is repeated. 我试图使用AJAX技术从MySQL数据库动态检索数据到网页,但重复div内容。 I want to refresh the div without duplicate the information. 我想刷新div而不重复信息。

here is the code 这是代码

api.php api.php

<?php 

require 'db.php';
$query = "SELECT * FROM variables"; 
$result = mysqli_query($con,$query);           
$data = array();
while ( $row = mysqli_fetch_row($result) )
{
  $data[] = $row;
 }
echo json_encode( $data );
?>

client.php client.php

  <html>
   <head>
    <script language="javascript" type="text/javascript" src="jquery.js"> 
     </script>
     </head>
      <body>

        <h2> Client example </h2>
        <h3>Output: </h3>

         <div id="output"></div>

         <script id="source" language="javascript" type="text/javascript">

         function ajaxcall() 
           {
           $.ajax({                                      
            url: 'api.php', data: "", dataType: 'json', timeout:2000, 
           success: function(rows)        
            {
            for (var i in rows)
                {
               var row = rows[i];          
                var id = row[0];
                   var vname = row[1];
              $('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname)
              .append("<hr />");
               }

              } 
              });
                }; 
                   ajaxcall();
                   setInterval(ajaxcall, (1 * 1000));

                 </script>
                 </body>
                </html>

Just change this 改变这个

 success: function(rows)        
            {
            for (var i in rows)

to this 对此

success: function(rows)        
            {
            $('#output').html(''); // empty the container div and append new HTML
            for (var i in rows)

try to use $('output').empty(); 尝试使用$('output').empty(); before the loop in order to avoid duplicating content. 在循环之前,以避免重复内容。

Another way you can do it as: 另一种方法可以做到:

var htmlData = '';
for (var i in rows)
     {
      var row = rows[i];          
      var id = row[0];
      var vname = row[1];
      htmlData + ="<b>id: </b>"+id+"<b> name: </b>"+vname+"<hr />";
   }
$('#output').html(htmlData);

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

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