【问题标题】:jQuery DataTable with SQLSRV and JSON带有 SQLSRV 和 JSON 的 jQuery 数据表
【发布时间】:2016-07-20 17:54:43
【问题描述】:

我不明白我做错了什么。这不是执行 ajax 调用并返回 JSON 的正确格式吗?

我正在尝试返回 JSON 以填充 DataTable。我以前做过与此非常相似的事情,但这次我无法让它工作。

这是我使用 SQLSRV 返回 JSON 的脚本(“api/exceptions_all.php”):

 <?php
   include("../include/database.php");

   $select = "SELECT
               ''
               ,[FOR_PARTNER] 
               ,[FOR_NAME]
               ,[SHP_PARTNER]
               ,[SHP_NAME]
               ,[MODDATE]
               ,[MODUSER]
               ,[ID]
             FROM [main].[dbo].[for_exceptions]";

 $query = sqlsrv_query($dbc, $select) or die(sqlsrv_errors());
 $out = array();

 while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) ) 
 {
   $out[] = $row;
 }
 echo json_encode( $out );
 sqlsrv_free_stmt($query);

 ?>

现在这是我的 javascript 文件(“exceptions.js”),我试图在其中检索 JSON 并将其打印到数据表中:

 $(document).ready(function()
 {
   var $dataTable = $('#example1').DataTable({
     "type": 'POST',
     "ajax": 'api/exceptions_all.php',
     "data": data,
     "dataType": 'json',
     "bDestroy": true
   });
 });

我不断收到一条错误消息,指出“未捕获的 ReferenceError:未定义数据”,指的是“数据”:上面的数据。

在我的 HTML 文件中,我有一个应该填充 DataTable 的表格:

 <table id="example1">
 <thead>
   <tr>
     <th>Edit</th>
     <th>FF Partner Code</th>
     <th>FF Name</th>
     <th>SHP Partner Code</th>
     <th>SHP Name</th>  
     <th>Modified Date</th>
     <th>Modified User</th>
     <th>ID</th>
   </tr>
 </thead>
 // datatable should be here
 </table>

【问题讨论】:

    标签: javascript php jquery json datatables


    【解决方案1】:

    你在 while 循环之外声明 $out[] 数组时缺少的东西;

         <?php
         include("../include/database.php");
    
         $select = "SELECT
               ''
               ,[FOR_PARTNER] 
               ,[FOR_NAME]
               ,[SHP_PARTNER]
               ,[SHP_NAME]
               ,[MODDATE]
               ,[MODUSER]
               ,[ID]
             FROM [main].[dbo].[for_exceptions]";
    
         $query = sqlsrv_query($dbc, $select) or die(sqlsrv_errors());
    
         $out=array();**// add this line** 
         while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) ) 
         {
         $out[] = $row;
         }
         echo json_encode( $out );
         sqlsrv_free_stmt($query);
    
       ?>
    

    【讨论】:

    • 对不起 - 我确实有你提到的那条线。我刚刚编辑了我的问题。然而,仍然有同样的问题。
    【解决方案2】:

    看起来您正在使用 jQuery 的 DataTables 插件...

    可能是这样的......

    $(document).ready(function()
    {
       var $dataTable = $('#example1').DataTable({
         "ajax": 'api/exceptions_all.php'
       });
    });
    

    这是直接来自文档...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 2020-11-19
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      相关资源
      最近更新 更多