【问题标题】:How to parse Json data, which is made by select mysql query?如何解析由select mysql查询生成的Json数据?
【发布时间】:2015-04-20 10:01:16
【问题描述】:

我的服务器代码正在返回 json 数据,其中包含 select mysql 查询。现在我必须解析这些信息,我需要将 json 信息填充到表中,我将如何做到这一点?

我的服务器代码

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","2323");
mysql_select_db("service");

if(isset($_POST['type']))
{
    if($_POST['type']=="carpenter"){
        $startDate=$_POST['startDate'];
        $endDate=$_POST['endDate'];
        $query="select * from booking where scheduledDate between $startDate AND $endDate"; 
        $result=mysqi_query($query);
        $count=mysql_num_rows($result);         
        $retVal=array();

        while($row=mysqli_fetch_assoc($result)){
            $$retVal[]=$row;
        }
        echo json_encode($retVal);
    }
} else{
    echo "Invalid Format";
}

我的脚本

<script>
    function fetchData2(){
      $(".data-contacts2-js tbody").empty();
      var startDate=$('#datepicker1').val();
      var endDate=$('#datepicker2').val();
      $.ajax({
              url: "http://localhost/service/cleaning.php",
              type:"POST",
              dataType:"json",
              data:{type:"carpenter", startDate:startDate, endDate:endDate},
              ContentType:"application/json",
              success: function(response){                           
                 alert(obj);
             },
             error: function(err){
                alert("fail");
            }       
        });             
     }  

     $(document).ready(function(){
         $(".data-contacts2-js tbody").empty();               
         $('#fetchContacts2').click(function() {
                 fetchData2();
         });
      });

 </script>

我的 html 代码

<div class="block-content collapse in">
      <div class="span12">
        <table class="data-contacts2-js table table-striped" >
             <thead>
                    <tr>
                          <th>ID</th>
                          <th>Customer Name</th>
                          <th>Customer Mobile</th>
                          <th>Customer Email</th>
                          <th>Address</th>
                          <th>Date</th>
                          <th>Time</th>
                          <th>Status</th>
                    </tr>
          </thead>
             <tbody>

             </tbody>
      </table>                                  
  </div>
 <button id="fetchContacts2" class="btn btn-default" type="submit">Refresh</button>                         
          </div>

我的 Json 格式是

[
    {
        "b_id": "101",
        "cust_name": "qwq",
        "cust_mobile": "323232323",
        "cust_email": "u@gmail.com",
        "cust_address": "kslaksl",
        "scheduledDate": "2015-02-26",
        "scheduledTime": "14:30:00",
        "sc_id": "3",
        "sps_id": "1"
    }
]

我的数据库表:

【问题讨论】:

  • 您可以使用$.each 从响应中构建您的标记表行,然后只需在tbody 上使用.html(markup)。这是错字吗? $result=mysqi_query($query);
  • @Ghost,谢谢你的回复,你能解释更多吗..
  • 你能显示你的 json 响应吗
  • @Outlooker,感谢您的回复,我添加了我的数据库快照,请查看,我是 JSon 的新手,我不知道如何响应..
  • @neelabhsingh 只需在成功块中使用该函数$.each(response, function(index, element){ // build html here }); 并删除您不需要的ContentType:"application/json",

标签: php jquery mysql ajax json


【解决方案1】:

$.each() 函数可用于迭代任何集合,无论是对象还是数组。在数组的情况下,回调每次都会传递一个数组索引和一个对应的数组值。在 ajax 成功中尝试每个函数并遍历从php 文件接收到的响应数据。希望能给你一个想法伙伴.. :)

        success: function(response){                           
             $.each(response, function(idx, obj) {
                $('table tbody').append(
                $('<tr>')
                    .append($('<td>').append(obj.id))
                    .append($('<td>').append(obj.cust_email))
                    .append($('<td>').append(obj.cust_mobile))
                );
             });
         },

仅供参考

$.each

【讨论】:

  • yes idx 表示索引..检查更新的答案伴侣。
【解决方案2】:

一种方法是使用$.each 并开始构建您的标记表行,然后将其放入tbody 标记内。

您可以在成功块内构建它们。这是基本思想。

$.ajax({
    url: "http://localhost/service/cleaning.php",
    type: "POST",
    dataType: "json",
    data: {type:"carpenter", startDate:startDate, endDate:endDate},
    success: function(response){                
        var rows = '';           
        $.each(response, function(index, element){
            rows += '<tr>'; // build the row
                $.each(element, function(key, val){
                    rows += '<td>' + val + '</td>'; // build the value
                });
            rows += '</tr>';
        });
        $('table tbody').html(rows);
    }   
});

旁注:根据您的代码,混合 MySQLi 和 MySQL 函数。

必填事项:

Please, don't use mysql_* functions in new code。它们不再维护and are officially deprecated。看到red box?改为了解prepared statements,并使用PDOMySQLi - this article 将帮助您决定哪个。如果你选择 PDO,here is a good tutorial

我建议将 PDO 与准备好的语句一起使用:

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
$db = new PDO('mysql:host=localhost;dbname=service', 'root', '2323');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if(isset($_POST['type'])) {
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];
    $query = 'SELECT * FROM booking WHERE scheduledDate BETWEEN :startDate AND :endDate'; 
    $select = $db->prepare($query);
    $select->bindParam(':startDate', $startDate);
    $select->bindParam(':endDate', $endDate);
    $select->execute();

    $data = $select->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data);
    exit;
}

【讨论】:

  • @neelabhsingh 不,你不需要这样的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 2015-05-22
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多