【问题标题】:How to add rows to jquery table from mysql query with ajax?如何使用ajax从mysql查询向jquery表添加行?
【发布时间】:2016-05-02 23:33:44
【问题描述】:

我需要从 AJAX 向 jQuery DataTable 中插入行。在 AJAX 中,当我对我的 mySql 数据库进行查询时,我调用了一个 PHP 文件,但我只在行中显示了一个字符。是因为返回的格式不正确,但是我无法解析正确的格式。

$query = "..myquery..";
if ($row = mysql_fetch_array($sql)) {
    do {
        $arr []= $row['name'];
    } while ($row = mysql_fetch_array($sql));
    echo json_encode($arr); // Here I tried return array without json_encode and a lot of things...
}

我知道用.DataTable().row.add() 添加行的格式如下,但我没有得到所需的格式。

[["Element software"], ["Software dist"],["Global envir"], ["Software"], ["Software list"]] 

如何在回显中获取此格式以返回此内容? 谢谢!

【问题讨论】:

    标签: php jquery mysql ajax datatables


    【解决方案1】:

    是数组的array,所以需要push一个数组到$arr,而不是字符串:

    $query = "..myquery..";
    $arr = []; // init an empty array
    // no need to do if() and do{}while() inside. You can just while(){} it
    while($row = mysql_fetch_array($sql)){ 
        $arr[]= [$row['name']]; // <== these square brackets do the trick  
    }
    echo json_encode($arr); // still need to json_encode
    

    【讨论】:

      【解决方案2】:
      do{
          $arr[]= array($row['name']);
      } while ($row = mysql_fetch_array($sql));
      echo json_encode($arr);
      

      注意

      $arr[]= array($row['name']);
      

      而不是

      $arr []= $row['name'];
      

      【讨论】:

        【解决方案3】:

        一:二运行mysql_fetch_array($sql) 因为php返回null;

        二:插入表格的代码ajax。

         $.ajax({
                        dataType:"json",
                        url:"recive.php",
                        type:"POST",
                        data:{id:id},
                        success: function(res){
                             for(var j=0;j<res.length;j++)
                                {
                                     $("#tabel").append("<table ><tr><td style='width:100%;' > "+res[j].id+"</td></tr></table>");
                                }    
                        }
        

        【讨论】:

          猜你喜欢
          • 2018-08-21
          • 1970-01-01
          • 2017-08-23
          • 1970-01-01
          • 2021-04-11
          • 2012-01-25
          • 2012-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多