使用jQuery从MySQL数据库中获取数据到数据表中

时间:2018-08-07 08:35:51

标签: datatable datatables datatables-1.10 angular-datatables

我已经开发了一个mysql数据库和一个php代码。在PHP代码中,我使用jQuery(ajax调用)从数据库中获取数据。在html文件中,我仅打印了数据表的表头。我想从数据库中获取其余数据。代码给出:


HTML代码:

<div class="container box">
     <div class="table-responsive">
            <div id="alert_message"></div>
            <table id="example" class="display">
               <thead>
                  <tr>
                     <th>Student ID</th>
                     <th>Student Name</th>
                     <th>Email ID</th>
                     <th>Mobile</th>
                     <th>Status</th>
                  </tr>
               </thead>
            </table>
         </div>
      </div>

jQuery代码:

<script>
    $(document).ready(function() {
        $('#example').dataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "fetch.php",
                "type": "GET",
                "datatype": "json"
            }
        });
    });
</script>

fetch.php

<?php
$connect = mysqli_connect("localhost","root","","lib");
$sql = "SELECT StudentId, FullName, EmailId, MobileNumber, Status  FROM tblstudents";
$result = mysqli_query($connect,$sql);

$json_array = array();

while ($row = mysqli_fetch_assoc($result)) 
{
    $json_array[] = $row;
}

echo json_encode($json_array);
?>

仍然没有将数据打印在数据表中。 jQuery需要进行哪些更改?

2 个答案:

答案 0 :(得分:0)

在jQuery Datatables中,不仅可以从ajax调用中获取数据。您还可以管理页面排序,搜索。

首先,您必须像这样修改javascript。

import javax.inject._
import models.Response
import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import _root_.controllers.JSONHelper.ResponseWrites

import scala.concurrent._

class ErrorHandler @Inject()(env: Environment,
                              config: Configuration,
                              sourceMapper: OptionalSourceMapper,
                              router: Provider[Router])
  extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  override protected def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    Future.successful(
      NotFound(Json.toJson(Response(isSuccess = false,"Resource Not Found", ("", ""))))
    )
  }

}

然后,在浏览器的开发人员工具->网络点击中可以看到,所有想要搜索,排序和排序的参数都将通过ajax调用传递。

您可以在ajax页面(在您的情况下为fetch.php)中通过print_r($ _ POST)进行查看,并在浏览器的开发人员工具->网络点击中在ajax上查看它。

您可以按以下方式收集所有信息,

$(document).ready(function() {
        $('#example').dataTable({
            "bProcessing": true,
            "serverSide": true,
            "ajax": {
                "url": "fetch.php",
                "type": "post"
            },
                error: function () {  // error handling code
                    $("#example").css("display", "none");
                }
        });
    });

然后您可以按以下方式构建查询

    $order_by = $_POST['order']; // This array contains order information of clicked column
    $search = $_POST['search']['value']; // This array contains search value information datatable
    $start = $_POST['start']; // start limit of data
    $length = $_POST['length']; // end limit of data
    $order_type = $order_by[0]['dir'];
    if ($order_by[0]['column']==0){
        $order_column = "table_column_name_of_the_first_column_in_the_datatable";
    } elseif ($order_by[0]['column']==1){
        $order_column = "table_column_name_of_the_second_column_in_the_datatable";
    }

然后获取总记录数,您可以执行以下操作,

if ($search!='' || $search!=NULL) {
    $str = "WHERE column_name_to_search LIKE '%$search%' OR column_name_to_search LIKE '%$search%' ";
} else {
    $str = "";
}
$data[][] = array(); 
$i = 0;
$sql = $connection->query("SELECT * FROM your_table $str ORDER BY $order_column $order_type LIMIT $start,$length");
while ($row_1 = $sql->fetch_assoc()){
    $data[$i] = array($row_1['column_1'],$row_1['column_2']);
    $i++;
}

最终构造将发送到正面视图的json输出。

$sql_2 = $connection->query("SELECT COUNT(*) AS all_count FROM your_table $str");
$row_2 = $sql_2->fetch_assoc();
$totalRecords = $row_2['all_count'];
if ($totalRecords==0){
    $data = array();
}

那行得通。

答案 1 :(得分:0)

我知道这真的很晚,但是我使用了与您完全相同的代码(顺便感谢!),对我来说起作用的是简单地添加到JQuery代码中:

dataSrc =''(在url ='...'之后)

,以便DataTables知道它正在加载数组。放进去使代码工作正常!