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 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件