【问题标题】:Load db data into javascript file将 db 数据加载到 javascript 文件中
【发布时间】:2018-06-11 10:16:26
【问题描述】:

我正在使用Laravel 5.5,我正在尝试使用ag-grid,并希望将来自我的数据库的数据直接加载到Javascript文件中。

我的迁移如下所示:

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

我的前端如下所示:

example.js

// specify the columns
var columnDefs = [
    {headerName: "Name", field: "name"},
    {headerName: "Created_At", field: "created_at"},
    {headerName: "Updated_At", field: "updated_at"}
];

// specify the data
var rowData = [
    {name: "TODO 1", created_at: "01.01.2018", updated_at: "05.11.2016"},
    {name: "TODO 1", created_at: "01.01.2018", updated_at: "05.11.2016"} // here I would like to replace this dummy data with my db data
];

// let the grid know which columns and what data to use
var gridOptions = {
    columnDefs: columnDefs,
    rowData: rowData,
    onGridReady: function () {
        gridOptions.api.sizeColumnsToFit();
    }
};

// used in our jasmine test
function selectAllRows() {
    gridOptions.api.selectAll();
}

// wait for the document to be loaded, otherwise ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function () {
    // lookup the container we want the Grid to use
    var eGridDiv = document.querySelector('#myGrid');

    // create the grid passing in the div to use together with the columns & data we want to use
    new agGrid.Grid(eGridDiv, gridOptions);
});

home.blade.php

<html>

<head>
    <script src="https://www.ag-grid.com/dist/ag-grid/ag-grid.js"></script>
    <script src="example.js"></script>
</head>

<body>
    <h1>Ag-Grid Example</h1>
    <div id="myGrid" style="height: 115px;width:500px" class="ag-fresh"></div>

    <!-- Own Scripts -->
    <script src="{{ asset('js/example.js') }}"></script>
</body>

</html>

有什么建议可以将我从数据库加载的数据插入到我的example.js 文件中的变量rowData 中?

感谢您的回复!

【问题讨论】:

    标签: javascript php laravel laravel-5


    【解决方案1】:

    如果您将数据作为集合获取,则可以像这样传递数据:

    <script>
        var app = {{ $collection }};
    </script>
    

    如果是数组,可以使用@json指令:

    <script>
        var app = @json($array);
    </script>
    

    您也可以使用其中一个可用的包或将数据放入hidden input HTML 元素中,以便能够在 JS 中使用这些数据。

    【讨论】:

      猜你喜欢
      • 2020-06-15
      • 2012-03-06
      • 1970-01-01
      • 2022-11-27
      • 2014-07-08
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多