php数据库查询后如何使javascript工作?

时间:2014-10-24 16:59:05

标签: javascript php jquery twitter-bootstrap

我在我的网站上使用bootstrap框架,javascript(jquery)和php。 所以基本我想按一个按钮,按下它,我们查询数据库并返回结果,结果将显示在bootstrap javascript powered modal中:因为popup模式是用javascript写的,它运行在php之后,$ row总是显示为未定义。我想知道是否有办法在js之前运行php?

<form action="" method="post">
<input type="text" id="field" name="field">
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" name="submit" id="submit">
Launch demo modal
</button>
</form>
<?php
if(isset($_POST['submit'])){
    $link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " .     mysqli_error($link)); 

   //consultation: 

   $query = "SELECT name FROM mytable" or die("Error in the consult.." . mysqli_error($link)); 

   //execute the query. 

   $result = mysqli_query($link, $query); 

   //display information: 

   if ($row = mysqli_fetch_array($result)) { 



   ?>

    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
     <div class="modal-dialog">
      <div class="modal-content">
       <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
          <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
     <div class="modal-body">
    <?php echo $row["name"] . "<br>"; ?>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>
  </div>
</div>

 <?php
 }
 }
 ?>

1 个答案:

答案 0 :(得分:2)

最好将此数据请求分离为AJAX请求,然后在AJAX成功回调中打开模式。

示例:

ajax_handler.php:

if(isset($_POST['submit'])){
    $link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " .     mysqli_error($link)); 

   //consultation: 

 $query = "SELECT name FROM mytable";

   //execute the query. 

 $result = mysqli_query($link, $query); 

 $rows = mysqli_fetch_array($result);
 //always wrap a response in an 'object' (associative array)
 //more infor here: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/
 echo json_encode(array('result' => $rows));
}

js code:

$("#submit").on('click', function(){
    $.post('ajax_handler.php', {submit: true}, function(data){
         var data = JSON.parse(data), markup = '';
         for(var i = 0; i < data.result.length; i++){
              markup = markup + '<div>' + data.result[i] + '</div>';
         }
         $('myModal').modal('open');
         $('.modal-body').append(markup)

    });
});

标记:

<button class="btn btn-primary btn-lg" id="submit">