Javascript,AJAX将MySQL内容导入div

时间:2013-08-26 03:49:25

标签: mysql ajax html get swap

我想将MySql数据库中的数据与一个或多个div中的默认内容交换而不重新加载页面。我在Dreamweaver CS6中使用'set text of container'javascript行为插入了PHP代码但没有成功。

如果有人能告诉我怎么做,我将非常感激。

1 个答案:

答案 0 :(得分:0)

save your php code in a file named getinfo.php then call it with ajax

<?php
  include("connectdatabase.php");

  $sql="SELECT * FROM table ORDER BY id DESC";
  $result=mysqli_query($con,$sql);

  $i = 1;
  while ($row = $result->fetch_assoc()) {
    echo "<tr>";
    echo "<td>" . $i . "</td>";
    echo "<td>" . $row["Name"] . "</td>";
    echo "<td>" . $row["Score"] . "</td>";
    echo "</tr>";
    $i++;
  }
  mysqli_close($con);
?>

在您的主文件中使用此

<div class="scoreBoard"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
  setInterval( refreshScoreBoard, 5000 );
  var inRequest = false;
  function refreshScoreBoard() {
    if ( inRequest ) {
      return false;
    }
    inRequest = true;
    var load = $.get('getinfo.php');
    $(".scoreBoard").html('Refreshing');
    load.error(function() {
      console.log( "Error" );
      // do something here if request failed
    });
    load.success(function( res ) {
      console.log( "Success" );
      $(".scoreBoard").html('<table>'+res+'</table>');
    });
    load.done(function() {
      console.log( "Completed" );
      inRequest = false;
    });
  }
</script>