【问题标题】:How to pass correctly a php json_encode value to a table that is using DataTables plugin?如何正确地将 php json_encode 值传递给使用 DataTables 插件的表?
【发布时间】:2020-10-18 00:45:31
【问题描述】:

我正在开发一个使用支付网关的项目,我想以 JSON 格式将支付 API 中的值显示到使用 Datatable JS plugin 的表格中。首先,我发现了一些与我的疑问相关的类似问题,但不幸的是,我很难找到正确的方法来解决这个问题。

  1. Using jQuery AJAX to pass JSON Object to PHP file
  2. How to parse nested JSON object in ajax using DataTables
  3. How to pass JSON object to PHP
  4. How to pass json object using PHP in Wepay API
  5. Display JSON object using DataTables

我正在使用一个调用 URL API 并以 JSON 格式获取结果的 php Curl 脚本:

all_payments.php

<?php 

$token = "TOKEN_PROD";

$ch = curl_init('URL_API');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
   'Content-Type: application/json',
   'Authorization: Bearer ' . $token
   ));

$data = curl_exec($ch);

$info = curl_getinfo($ch);

echo $data;

curl_close($ch);

?>

以下是执行上述Curl脚本时JSON格式的API结果:

{
    "results": [
        {
            "metadata": {},
            "corporation_id": null,
            "operation_type": "regular_payment",
            "fee_details": [],
            "notification_url": null,
            "date_approved": null,
            "money_release_schema": null,
            "payer": {
                "first_name": "Test",
                "last_name": "Test",
                "email": "test_user_80534729@test.com",
                "identification": {
                    "number": "34579430",
                    "type": "DNI"
                },
                "phone": {
                    "area_code": "01",
                    "number": "1111-1111",
                    "extension": ""
                },
                "type": "registered",
                "entity_type": null,
                "id": "660948681"
            },
            "transaction_details": {
                "total_paid_amount": 10,
                "acquirer_reference": null,
                "installment_amount": 0,
                "financial_institution": "",
                "net_received_amount": 0,
                "overpaid_amount": 0,               
                "payable_deferral_period": null,
                "payment_method_reference_id": "1848987916",
                "verification_code": "1343987916"
            },
            "statement_descriptor": null,
            "call_for_authorize_id": null,
            "installments": 1,
            "pos_id": null,
            "external_reference": null,
            "date_of_expiration": "2020-10-20T22:59:59.000-04:00",
            "charges_details": [],
            "id": 1453987916,
            "payment_type_id": "ticket",
            "barcode": {
                "content": "23791841402309310003380250122998791600633330"
            },
            "order": {
                "id": "1820096336",
                "type": "mercadopago"
            },
            "counter_currency": null,
            "brand_id": null,
            "status_detail": "pending_waiting_payment",
            "differential_pricing_id": null,
            "additional_info": {
                "ip_address": "123.456.678.890",
                "nsu_processadora": null,
                "available_balance": null
            },
            "live_mode": false,
            "marketplace_owner": null,
            "card": {},
            "integrator_id": null,
            "status": "pending",
            "transaction_amount_refunded": 0,
            "transaction_amount": 10,
            "description": "Short",
            "money_release_date": null,
            "merchant_number": null,
            "refunds": [],
            "authorization_code": null,
            "captured": true,
            "collector_id": 58546234946,
            "merchant_account_id": null,
            "taxes_amount": 0,
            "date_last_updated": "2020-10-17T11:30:31.000-04:00",
            "coupon_amount": 0,
            "store_id": null,
            "date_created": "2020-10-17T11:30:31.000-04:00",
            "acquirer_reconciliation": [],
            "sponsor_id": null,
            "shipping_amount": 0,
            "issuer_id": null,
            "payment_method_id": "ticket",
            "binary_mode": false,
            "platform_id": null,
            "deduction_schema": null,
            "processing_mode": "aggregator",
            "currency_id": "USA",
            "shipping_cost": 0
        }
    ]
}

基于上面的 JSON 结果,我正在尝试将一些 JSON 对象传递到使用 Datatables 插件的表中。以下是使用 Datatable 插件显示表格的 html 和 javascript 代码:

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">

<script src="jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>

<table id="example" class="display" width="100%">
    
   <thead>
       <tr>
            <th>id</th>
            <th>date created</th>
            <th>email</th>
            <th>total_paid_amount</th>
            <th>status</th>
       </tr>
   </thead>
    
</table>

<script>

    $(document).ready(function() {

    $('#example').DataTable({

          "ajax": {
          "url": "all_payments.php",
          "dataSrc": "results"
            },
        "columns": [
            { "data": "id" },
            { "data": "date_created" },
            { "data": "email" },
            { "data": "total_paid_amount" },
            { "data": "status" }
        ]
    });
    });
    
    </script>

当带有 Datatable 的页面重新加载时,我在浏览器控制台上收到错误:

Uncaught TypeError: Cannot read property 'length' of undefined
    at jquery.dataTables.min.js:65
    at h (jquery.dataTables.min.js:52)
    at Object.success (jquery.dataTables.min.js:52)
    at c (jquery-3.5.1.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-3.5.1.min.js:2)
    at l (jquery-3.5.1.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery-3.5.1.min.js:2)

在这种情况下,我如何改进 Curl php 脚本 (all_payments.php) 以将 JSON 正确传递给使用 Datatables 插件的表?我尝试替换:

echo $data;

$decode = json_decode($data,true);

    foreach ( $decode["results"] as $value){
        echo $value["id"];
        echo $value["date_created"];
        echo $value["email"];
        echo $value["total_paid_amount"];
        echo $value["status"];
    }

但它不起作用。

【问题讨论】:

    标签: php json datatables


    【解决方案1】:

    我找到了解决方案。我编辑了 all_payments.php 脚本如下:

    <?php
    
    //setup your token payment or others
    $token = "PROD_TOKEN";
    
    //setup the request, you can also use CURLOPT_URL
    $ch = curl_init('API_URL');
    
    // Returns the data/output as a string instead of raw data
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    //Set your auth headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
       'Content-Type: application/json',
       'Authorization: Bearer ' . $token
       ));
    
    // get stringified data/output. See CURLOPT_RETURNTRANSFER
    $data = curl_exec($ch);
    
    // get info about the request
    $info = curl_getinfo($ch);
    
    header('Content-Type: application/json');
    
    $new_array = array(); // this array should be empty
    
    $decode = json_decode($data);
    
    // access property of object in array
    echo '{"data":';
    foreach($decode->results as $item) {
      $new_array[] = array(
        'id' => $item->{'id'},'date_created' => $item->{'date_created'}, 'email' => $item -> payer ->{'email'}, 'total_paid_amount' => $item -> transaction_details ->{'total_paid_amount'}
        );  
    }
    
    echo json_encode($new_array);
    
    echo '}';
    // close curl resource to free up system resources
    curl_close($ch);
    
    
    ?>
    

    foreach 上,脚本获取对象值,然后将结果传递给数据表,将 json 值输出,如下代码:

    <table id="example" class="display" width="100%">
        
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Date Created</th>
                    <th>Email</th>
                    <th>Total</th>
                </tr>
            </thead>
        
    </table>
    
    <script>
        $(document).ready(function() {
      
        $('#example').DataTable( {
    
            "ajax": "all_payments.php",
            "columns": [
                { "data": "id" },
                { "data": "date_created" },
                { "data": "email" },
                { "data": "total_paid_amount",
                
                    render: $.fn.dataTable.render.number( ',', '.', 2, '$ ' )
                    
                },
            ],
            
        "columnDefs":[
            {"targets":1, render:function(data){
          return moment(data).format('MM/DD/YYYY');
        }},
        
                {"targets": 3,
            "className": 'dt-body-right'}
        
        ]
    
        });
      
        });
        
        
        </script>
    

    就是这样。如果有人想改进此代码,请随意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2021-07-12
      • 2014-04-02
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      相关资源
      最近更新 更多