doufan9395 2018-10-23 17:51
浏览 61
已采纳

我想创建一个包含php变量的文件.json?

I want to create a file named "file.json.php"

Which contains vars from PHP like $_POST['foo'].

This file will generate diferents results depending on the value of the value of post var passed by an ajax call.

What configurations are necessary to make an ajax for call file.php.json and how can pass an array as parameters to json file?

jqxhr = $.ajax('../files/data/file.json').

This is the Json file.

{
"data": [{
    "work": "Symfony No. 3 in D minor",
    "id": "1",
    "composer": "Anton Bruckner"
}, {
    "work": "Violin Concerto in E minor",
    "id": "2",
    "composer": "Mendelssohn Felix"
}, {
  "work": "Symfony No.1 in C major",
  "id": "3",
  "composer": "Beethoven, Ludwig van"
}, {
    "work": "Solution for dynamic headers in datatables",
    "id": "4",
    "composer": "Fasani, Guza"
  }],
"columns": [
                    {
                        "data": "work",
                        "name": "Work"
                    },
                    {
                        "data": "id",
                        "name": "Product ID"

                    },
                    {
                        "data": "composer",
                        "name": "Composer"
                    }
            ]
   }
  • 写回答

1条回答 默认 最新

  • dongwei5794 2018-10-24 19:40
    关注

    Finally i made a file end-named with the php extension file.json.php, and manage it like a php normal file but adding an echo with the function json_encode().

    This is a extract of how i made the file.

      //only making to arrays an array (in this case for datatables dynamic columns on the fly)
    
        $columns[] = array("data" => "id", "name"=>"Id");
        $columns[] = array("data" => "number", "name"=>"numeroItem");
        $columns[] = array("data" => "item", "name"=>"Item");
    
        $a = array();
        $a['id'] = $row[$k]['id'];
        $a['number'] = $row[$k]['number'];
        $a['item']= $row[$k]['Item'];
    
    
        $data[] = $a;
    
        $json_for_datatable = array("columns" => $columns, "data" => $data);
    
        echo json_encode($json_for_datatable);
    

    For configuration or considerations is necessary to receive de responseText with the function JSON.parse(), ¡This is important!

    data = JSON.parse(jqxhr.responseText);
    

    For considering in the ajax call

    var data,
                tableName = '#exampleTablaDinamica'+$(this).attr("data-id"),
                columns, str,
                jqxhr = $.ajax('../files/data/data.json.php?idPartida='+$(this).attr("data-idpartida")+'&meses='+ selected +'&idPresupuesto='+$('#idPresupuesto').val())
                        .done(function () {
                            data = JSON.parse(jqxhr.responseText);
                // Iterate each column and print table headers for Datatables
                $(tableName + " thead").html("<tr></tr>");
    
                $.each(data.columns, function (k, colObj) {
                    str = '<th>' + colObj.name + '</th>';
                    $(str).appendTo(tableName+'>thead>tr');
                });
                // Add some Render transformations to Columns
                // Not a good practice to add any of this in API/ Json side
    
    
    
                data.columns[0].render = function (data, type, row) {
                    return data;
                }
                data.columns[1].render = function (data, type, row) {
                    return data;
                }
                data.columns[2].render = function (data, type, row) {
                    return "<a href='a.php'>" + data + "</a>";
                }
    
                // Debug?
                console.log(data.columns[0]);
    
                if ( $.fn.DataTable.isDataTable(tableName) ) {
                  $(tableName).DataTable().destroy();
    
                }
    
    
                table = $(tableName).dataTable({
                    "data": data.data,
                    "columns": data.columns,
                    "responsive":true,
                    "fnInitComplete": function () {
                        // Event handler to be fired when rendering is complete (Turn off Loading gif for example)
                        console.log('Datatable rendering complete');
                    }
                });
    
            })
            .fail(function (jqXHR, exception) {
                            var msg = '';
                            if (jqXHR.status === 0) {
                                msg = 'Not connect.
     Verify Network.';
                            } else if (jqXHR.status == 404) {
                                msg = 'Requested page not found. [404]';
                            } else if (jqXHR.status == 500) {
                                msg = 'Internal Server Error [500].';
                            } else if (exception === 'parsererror') {
                                msg = 'Requested JSON parse failed.';
                            } else if (exception === 'timeout') {
                                msg = 'Time out error.';
                            } else if (exception === 'abort') {
                                msg = 'Ajax request aborted.';
                            } else {
                                msg = 'Uncaught Error.
    ' + jqXHR.responseText;
                            }
                console.log(msg);
            });
    

    And finally this is the generated JSON content.

    {
    "columns": [{
        "data": "id",
        "name": "Id"
    }, {
        "data": "number",
        "name": "number"
    }, {
        "data": "item",
        "name": "Item"
    }, {
        "data": "10 2018",
        "name": "10 2018"
    }, {
        "data": "11 2018",
        "name": "11 2018"
    }, {
        "data": "total",
        "name": "total"
    }],
    "data": [{
        "id": "1",
        "number": "1.1",
        "item": "loremipsum  loremipsum  loremipsum  loremipsum  ",
        "10 2018": "0",
        "11 2018": "0",
        "total": "20.741"
    }]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab