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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题