【问题标题】:Using Jquery Ajax to retrieve data from Mysql使用 Jquery Ajax 从 Mysql 中检索数据
【发布时间】:2013-05-18 10:36:53
【问题描述】:

list.php:一个简单的ajax代码,我只想显示Mysql表的记录:

<html>

<head>
    <script src="jquery-1.9.1.min.js">
    </script>
    <script>
    $(document).ready(function() {
        var response = '';
        $.ajax({
            type: "GET",
            url: "Records.php",
            async: false,
            success: function(text) {
                response = text;
            }
        });

        alert(response);
    });
    </script>
</head>

<body>
    <div id="div1">
        <h2>Let jQuery AJAX Change This Text</h2>
    </div>
    <button>Get Records</button>
</body>

</html>

Records.php 是从 Mysql 获取记录的文件。
数据库中只有两个字段:“姓名”、“地址”。

<?php
    //database name = "simple_ajax"
    //table name = "users"
    $con = mysql_connect("localhost","root","");
    $dbs = mysql_select_db("simple_ajax",$con);
    $result= mysql_query("select * from users");
    $array = mysql_fetch_row($result);
?>
<tr>
    <td>Name: </td>
    <td>Address: </td>
</tr>
<?php
    while ($row = mysql_fetch_array($result))
    {
        echo "<tr>";
        echo "<td>$row[1]</td>";
        echo "<td>$row[2]</td>";
        echo "</tr>";
    }   
?>

此代码无效。

【问题讨论】:

  • 直接去Records.php会发生什么?是否有任何错误信息?您需要更准确地了解哪些不起作用。
  • “users”表中的列名是 1 还是 2?如果是,请尝试使用 echo "".$row['1']."";在records.php中
  • 你到底得到了什么输出?

标签: php mysql ajax jquery


【解决方案1】:

要使用 Ajax + jQuery 检索数据,您应该编写以下代码:

 <html>
 <script type="text/javascript" src="jquery-1.3.2.js"> </script>

 <script type="text/javascript">

 $(document).ready(function() {

    $("#display").click(function() {                

      $.ajax({    //create an ajax request to display.php
        type: "GET",
        url: "display.php",             
        dataType: "html",   //expect html to be returned                
        success: function(response){                    
            $("#responsecontainer").html(response); 
            //alert(response);
        }

    });
});
});

</script>

<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
   <tr>
       <td> <input type="button" id="display" value="Display All Data" /> </td>
   </tr>
</table>
<div id="responsecontainer" align="center">

</div>
</body>
</html>

对于mysqli连接,这样写:

<?php 
$con=mysqli_connect("localhost","root",""); 

为了显示数据库中的数据,你应该这样写:

<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($data = mysqli_fetch_row($result))
{   
    echo "<tr>";
    echo "<td align=center>$data[0]</td>";
    echo "<td align=center>$data[1]</td>";
    echo "<td align=center>$data[2]</td>";
    echo "<td align=center>$data[3]</td>";
    echo "<td align=center>$data[4]</td>";
    echo "</tr>";
}
echo "</table>";
?>

【讨论】:

  • 请注意:mysql_* 函数不再支持,它们是 officially deprecated不再维护并将被 @ 987654322@以后。您应该使用PDOMySQLi 更新您的代码,以确保您的项目在未来的功能。
  • 大家好,我尝试了上面的代码,但是它返回了完整的显示文件数据以及 php.ini 文件。请你让我知道可能是什么问题。我是 .net 开发人员,只是在 php 上工作。
  • @user3816325 检查您的服务器。我相信你的服务器没有运行。
  • 感谢它 100% 对我有用,我使用了 pdo 我想自定义它并将其发布给使用 pdo 的人
【解决方案2】:

你不能返回 ajax 返回值。您存储的全局变量在返回后存储您的返回值。
或者像这样更改您的代码。

AjaxGet = function (url) {
    var result = $.ajax({
        type: "POST",
        url: url,
       param: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
       async: false,
        success: function (data) {
            // nothing needed here
      }
    }) .responseText ;
    return  result;
}

【讨论】:

  • 没有 Json 我必须这样做。
  • @RaviParmar 更改数据类型“html”。例如。
【解决方案3】:

请确保您的 $row[1] , $row[2] 包含正确的值,我们在这里假设 1 = Name , and 2 here is your Address field

假设您已从 Records.php 中正确获取记录,您可以执行以下操作:

$(document).ready(function()
{
    $('#getRecords').click(function()
    {
        var response = '';
        $.ajax({ type: 'POST',   
                 url: "Records.php",   
                 async: false,
                 success : function(text){
                               $('#table1').html(text);
                           }
           });
    });

}

在您的 HTML 中

<table id="table1"> 
    //Let jQuery AJAX Change This Text  
</table>
<button id='getRecords'>Get Records</button>

小记:

尝试学习 PDO http://php.net/manual/en/class.pdo.php,因为不再鼓励 mysql_* functions..

【讨论】:

    【解决方案4】:
    $(document).ready(function(){
        var response = '';
        $.ajax({ type: "GET",   
             url: "Records.php",   
             async: false,
             success : function(text)
             {
                 response = text;
             }
        });
    
        alert(response);
    });
    

    需要:

    $(document).ready(function(){
    
         $.ajax({ type: "GET",   
             url: "Records.php",   
             async: false,
             success : function(text)
             {
                 alert(text);
             }
        });
    
    });
    

    【讨论】:

      【解决方案5】:
      This answer was for @
      Neha Gandhi but I modified it for  people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer 
      
          <html>
      <!--Save this as index.php-->
            <script src="//code.jquery.com/jquery-1.9.1.js"></script>
              <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
          
           <script type="text/javascript">
          
           $(document).ready(function() {
          
              $("#display").click(function() {                
          
                $.ajax({    //create an ajax request to display.php
                  type: "GET",
                  url: "display.php",             
                  dataType: "html",   //expect html to be returned                
                  success: function(response){                    
                      $("#responsecontainer").html(response); 
                      //alert(response);
                  }
          
              });
          });
          });
          
          </script>
          
          <body>
          <h3 align="center">Manage Student Details</h3>
          <table border="1" align="center">
             <tr>
                 <td> <input type="button" id="display" value="Display All Data" /> </td>
             </tr>
          </table>
          <div id="responsecontainer" align="center">
          
          </div>
          </body>
          </html>
      
      <?php
      // save this as display.php
      
      
          // show errors 
      error_reporting(E_ALL);
      ini_set('display_errors', 1);
          //errors ends here 
      // call the page for connecting to the db
      require_once('dbconnector.php');
      ?>
      <?php
      $get_member =" SELECT 
      empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials   FROM employees";
      $user_coder1 = $con->prepare($get_member);
      $user_coder1 ->execute();
      
      echo "<table border='1' >
      <tr>
      <td align=center> <b>Roll No</b></td>
      <td align=center><b>Name</b></td>
      <td align=center><b>Address</b></td>
      <td align=center><b>Stream</b></td></td>
      <td align=center><b>Status</b></td>";
      
      while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
      $firstName = $row['firstName'];
      $empid = $row['empid'];
      $lastName =    $row['lastName'];
      $cell =    $row['cell'];
      
          echo "<tr>";
          echo "<td align=center>$firstName</td>";
          echo "<td align=center>$empid</td>";
          echo "<td align=center>$lastName </td>";
          echo "<td align=center>$cell</td>";
          echo "<td align=center>$cell</td>";
          echo "</tr>";
      }
      echo "</table>";
      ?>
      
      <?php
      // save this as dbconnector.php
      function connected_Db(){
      
          $dsn  = 'mysql:host=localhost;dbname=mydb;charset=utf8';
          $opt  = array(
              PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
              PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
          );
          #echo "Yes we are connected";
          return new PDO($dsn,'username','password', $opt);
          
      }
      $con = connected_Db();
      if($con){
      //echo "me  is connected ";
      }
      else {
      //echo "Connection faid ";
      exit();
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 2012-02-21
        • 1970-01-01
        • 2012-05-02
        • 1970-01-01
        • 2014-02-05
        • 2010-10-04
        • 2022-08-14
        相关资源
        最近更新 更多