如何使用javascript和PHP导入数据Fuel UX datagrid

时间:2012-11-25 07:00:05

标签: php javascript jquery twitter-bootstrap fuelux

Fuel UX在这里: http://exacttarget.github.com/fuelux/

具体来说,我正在尝试使用Datagrid。

这是一个例子: http://code.exacttarget.com/code-examples/datagrid.html

我试图重新创建: https://raw.github.com/ExactTarget/fuelux/master/sample/data.js

只需通过PHP文件输出即可。我能够让PHP正确输出正确的数据并将其转储到主文件中,因此data.js文件现在在主PHP / HTML文件中输出,并使用这些标记在标题中包含我的所有信息:

<script></script>

并使用Gi​​tHub网站上的示例标记。

我似乎无法让它正常工作,是否有另一种方法将数据从PHP导入数据网格?是否应该更改data.js的一些代码,因为它现在正在主php / html文件中输出?

基本上尝试使用PHP从MySQL中提取数据,然后将其转储到数据网格中。我似乎找不到太多的文档,我想我的真正问题是将我的php应用程序中的数据导入Fuel UX Datagrid的最佳方法是什么?

1 个答案:

答案 0 :(得分:4)

使用php / mysql写入data.js,以sample / data.js为例。 (或将.php重命名为data.js并解析为php(Parse js/css as a PHP file using htaccess))。

setting fuelux datagrid source from backbone collection给出了正确的方向。

假设您有一个数据数据库表,其中包含以下字段:id,title和city,并且您希望在datagrid中显示它。

创建从mysql返回json格式的php文件(例子):

<强> data.php:

<?
error_reporting(E_ALL);
ini_set('report_errors','on');
$mysqli = new mysqli('localhost', 'root', '*******', 'cities');
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

$data = array();
if ($result = $mysqli->query('SELECT `id`,`title`,`city` FROM `poi`')) 
{

        //$data['testdata'] = mysqli_fetch_all($result,MYSQLI_ASSOC);
        while(($row=$result->fetch_assoc())){$data[]=$row;}
        $result->close();
}


header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($data);
exit;

创建静态数据源 testdatasource.js

/*
 * Fuel UX Data components - static data source
 * https://github.com/ExactTarget/fuelux-data
 *
 * Copyright (c) 2012 ExactTarget
 * Licensed under the MIT license.
 */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['underscore'], factory);
    } else {
        root.TestDataSource = factory();
    }
}(this, function () {

    var TestDataSource = function (options) {
        this._formatter = options.formatter;
        this._columns = options.columns;
        this._delay = options.delay || 0;
    };

    TestDataSource.prototype = {

        columns: function () {
            return this._columns;
        },

        data: function (options, callback) {
            var self = this;

            setTimeout(function () {
                var data;
                $.ajax({
                    url: '/data.php',
                    dataType: 'json',
                    async: false,
                    success: function(result) {
                        data = result;
                    }
                });

                                    // SEARCHING
                if (options.search) {
                    data = _.filter(data, function (item) {
                        var match = false;

                        _.each(item, function (prop) {
                            if (_.isString(prop) || _.isFinite(prop)) {
                                if (prop.toString().toLowerCase().indexOf(options.search.toLowerCase()) !== -1) match = true;
                            }
                        });

                        return match;
                    });
                }


                var count = data.length;

                // SORTING
                if (options.sortProperty) {
                    data = _.sortBy(data, options.sortProperty);
                    if (options.sortDirection === 'desc') data.reverse();
                }

                // PAGING
                var startIndex = options.pageIndex * options.pageSize;
                var endIndex = startIndex + options.pageSize;
                var end = (endIndex > count) ? count : endIndex;
                var pages = Math.ceil(count / options.pageSize);
                var page = options.pageIndex + 1;
                var start = startIndex + 1;

                data = data.slice(startIndex, endIndex);

                if (self._formatter) self._formatter(data);

                callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });

            }, this._delay)
        }
    };

    return TestDataSource;
}));

这将从data.php $.ajax({ url: '/data.php', dataType: 'json', async: false, success: function(result) { data = result; } });

构建数据集

在你的html中调用你的数据集并创建列:

var dataSource = new TestDataSource({
columns: [
{
property: 'id',
label: 'ID',
sortable: true
},
{
property: 'title',
label: 'Title',
sortable: true
},
{
property: 'city',
label: 'City',
sortable: true
}
],
delay: 250
});

使用此数据源初始化网格网格:

$('#MyGrid').datagrid({
dataSource: dataSource
});

获取datagrid:

  1. 从源代码(zip)下载并解压缩到/ fuelux-master /
  2. 创建/index.html
  3. <强>的index.html

    <!DOCTYPE html>
    <html lang="en" class="fuelux">
    <head>
    <meta charset="utf-8">
    <title>Fuel UX 2</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link href="./fuelux-master/dist/css/fuelux.css" rel="stylesheet">
    
    <script src="./fuelux-master/lib/require.js"></script>
    
    <style type="text/css">
    body {
    padding-bottom: 200px;
    }
    </style>
    
    <script>
    requirejs.config({
    paths: {
    'jquery': './fuelux-master/lib/jquery',
    'underscore': 'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min',
    'bootstrap': './fuelux-master/lib/bootstrap/js',
    'fuelux': './fuelux-master/src',
    'sample': './fuelux-master/sample'
    }
    });
    
    require(['jquery', 'sample/data', 'sample/datasource', 'sample/datasourceTree', 'fuelux/all'], 
    
    
    function ($, sampleData, StaticDataSource,datasourceTree) {
    
    
    // DATAGRID
    var dataSource = new StaticDataSource({
    columns: [
    {
    property: 'toponymName',
    label: 'Name',
    sortable: true
    },
    {
    property: 'countrycode',
    label: 'Country',
    sortable: true
    },
    {
    property: 'population',
    label: 'Population',
    sortable: true
    },
    {
    property: 'fcodeName',
    label: 'Type',
    sortable: true
    }
    ],
    data: sampleData.geonames,
    delay: 250
    });
    
    $('#MyGrid').datagrid({
    dataSource: dataSource
    });
    
    });
    </script>
    
    
    </head>
    
    <body>
    
    <div class="container">
    
    
    <!-- DATAGRID -->
    <table id="MyGrid" class="table table-bordered datagrid">
    
    <thead>
    <tr>
    <th>
    <span class="datagrid-header-title">Geographic Data Sample</span>
    
    <div class="datagrid-header-left">
    <div class="input-append search datagrid-search">
    <input type="text" class="input-medium" placeholder="Search">
    <button class="btn"><i class="icon-search"></i></button>
    </div>
    </div>
    <div class="datagrid-header-right">
    <div class="select filter" data-resize="auto">
    <button data-toggle="dropdown" class="btn dropdown-toggle">
    <span class="dropdown-label"></span>
    <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
    <li data-value="all" data-selected="true"><a href="#">All</a></li>
    <li data-value="lt5m"><a href="#">Population &lt; 5M</a></li>
    <li data-value="gte5m"><a href="#">Population &gt;= 5M</a></li>
    </ul>
    </div>
    </div>
    </th>
    </tr>
    </thead>
    
    <tfoot>
    <tr>
    <th>
    <div class="datagrid-footer-left" style="display:none;">
    <div class="grid-controls">
    <span>
    <span class="grid-start"></span> -
    <span class="grid-end"></span> of
    <span class="grid-count"></span>
    </span>
    <div class="select grid-pagesize" data-resize="auto">
    <button data-toggle="dropdown" class="btn dropdown-toggle">
    <span class="dropdown-label"></span>
    <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
    <li data-value="5" data-selected="true"><a href="#">5</a></li>
    <li data-value="10"><a href="#">10</a></li>
    <li data-value="20"><a href="#">20</a></li>
    <li data-value="50"><a href="#">50</a></li>
    <li data-value="100"><a href="#">100</a></li>
    </ul>
    </div>
    <span>Per Page</span>
    </div>
    </div>
    <div class="datagrid-footer-right" style="display:none;">
    <div class="grid-pager">
    <button type="button" class="btn grid-prevpage"><i class="icon-chevron-left"></i></button>
    <span>Page</span>
    
    <div class="input-append dropdown combobox">
    <input class="span1" type="text">
    <button class="btn" data-toggle="dropdown"><i class="caret"></i></button>
    <ul class="dropdown-menu"></ul>
    </div>
    <span>of <span class="grid-pages"></span></span>
    <button type="button" class="btn grid-nextpage"><i class="icon-chevron-right"></i></button>
    </div>
    </div>
    </th>
    </tr>
    </tfoot>
    </table>
    
    </div>
    </body>
    </html>
    

    在requirejs配置的路径中查看 ./ fuelux-master / 。另请参阅var dataSource的初始化以定义列。至少你需要用id =“MyGrid”来写表格的完整html。

    一些重构和使用CDN示例:http://plnkr.co/hZRjry5vG8ZcOG4VbjNq

    • 通过带有requirejs的CDN使用bootstrap和jQuery,请参阅Loading Bootstrap from CDN with Require.js
    • 用datagrid.js替换all.js的include( note ,如果没有select.js,datagrid将无效,select.js需要util.js)
    • 删除sample / datasourceTree,因为我们不需要它