flot js и yii2

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

flot js и yii2

Сообщение svil »

Пытаюсь настроить графическую библиотеку flot на yii2 без расширения, напрямую.
Без yii2 график выводится http://www.flotcharts.org/flot/examples ... index.html
Ошибка js:

Код: Выделить всё

Uncaught Error: Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4
    at bootstrap.js:15
    at bootstrap.js:17
js.js:53 Uncaught TypeError: $.plot is not a function
    at HTMLDocument.<anonymous> (js.js:53)
    at fire (jquery.js:974)
    at Object.fireWith [as resolveWith] (jquery.js:1084)
    at Function.ready (jquery.js:406)
    at HTMLDocument.DOMContentLoaded (jquery.js:83)
background.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)
вид:

Код: Выделить всё

<div id="header">
    <h2>Visitors</h2>
</div>

<div id="content">

    <div class="demo-container">
        <div id="placeholder" class="demo-placeholder"></div>
    </div>

    <div class="demo-container" style="height:150px;">
        <div id="overview" class="demo-placeholder"></div>
    </div>

    <p>This plot shows visitors per day to the Flot homepage, with weekends colored.</p>

    <p>The smaller plot is linked to the main plot, so it acts as an overview. Try dragging a selection on either plot, and watch the behavior of the other.</p>

</div>

<div id="footer">
    Copyright &copy; 2007 - 2014 IOLA and Ole Laursen
</div>

js.js

Код: Выделить всё

$(function() {

    var d = [[1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 77], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 676], [1197241200000, 1205], [1197327600000, 906], [1197414000000, 710], [1197500400000, 639], [1197586800000, 540], [1197673200000, 435], [1197759600000, 301], [1197846000000, 575], [1197932400000, 481], [1198018800000, 591], [1198105200000, 608], [1198191600000, 459], [1198278000000, 234], [1198364400000, 1352], [1198450800000, 686], [1198537200000, 279], [1198623600000, 449], [1198710000000, 468], [1198796400000, 392], [1198882800000, 282], [1198969200000, 208], [1199055600000, 229], [1199142000000, 177], [1199228400000, 374], [1199314800000, 436], [1199401200000, 404], [1199487600000, 253], [1199574000000, 218], [1199660400000, 476], [1199746800000, 462], [1199833200000, 448], [1199919600000, 442], [1200006000000, 403], [1200092400000, 204], [1200178800000, 194], [1200265200000, 327], [1200351600000, 374], [1200438000000, 507], [1200524400000, 546], [1200610800000, 482], [1200697200000, 283], [1200783600000, 221], [1200870000000, 483], [1200956400000, 523], [1201042800000, 528], [1201129200000, 483], [1201215600000, 452], [1201302000000, 270], [1201388400000, 222], [1201474800000, 439], [1201561200000, 559], [1201647600000, 521], [1201734000000, 477], [1201820400000, 442], [1201906800000, 252], [1201993200000, 236], [1202079600000, 525], [1202166000000, 477], [1202252400000, 386], [1202338800000, 409], [1202425200000, 408], [1202511600000, 237], [1202598000000, 193], [1202684400000, 357], [1202770800000, 414], [1202857200000, 393], [1202943600000, 353], [1203030000000, 364], [1203116400000, 215], [1203202800000, 214], [1203289200000, 356], [1203375600000, 399], [1203462000000, 334], [1203548400000, 348], [1203634800000, 243], [1203721200000, 126], [1203807600000, 157], [1203894000000, 288]];

    // first correct the timestamps - they are recorded as the daily
    // midnights in UTC+0100, but Flot always displays dates in UTC
    // so we have to add one hour to hit the midnights in the plot

    for (var i = 0; i < d.length; ++i) {
        d[i][0] += 60 * 60 * 1000;
    }

    // helper for returning the weekends in a period

    function weekendAreas(axes) {

        var markings = [],
            d = new Date(axes.xaxis.min);

        // go to the first Saturday

        d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
        d.setUTCSeconds(0);
        d.setUTCMinutes(0);
        d.setUTCHours(0);

        var i = d.getTime();

        // when we don't set yaxis, the rectangle automatically
        // extends to infinity upwards and downwards

        do {
            markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
            i += 7 * 24 * 60 * 60 * 1000;
        } while (i < axes.xaxis.max);

        return markings;
    }

    var options = {
        xaxis: {
            mode: "time",
            tickLength: 5
        },
        selection: {
            mode: "x"
        },
        grid: {
            markings: weekendAreas
        }
    };

    var plot = $.plot("#placeholder", [d], options);

    var overview = $.plot("#overview", [d], {
        series: {
            lines: {
                show: true,
                lineWidth: 1
            },
            shadowSize: 0
        },
        xaxis: {
            ticks: [],
            mode: "time"
        },
        yaxis: {
            ticks: [],
            min: 0,
            autoscaleMargin: 0.1
        },
        selection: {
            mode: "x"
        }
    });

    // now connect the two

    $("#placeholder").bind("plotselected", function (event, ranges) {

        // do the zooming
        $.each(plot.getXAxes(), function(_, axis) {
            var opts = axis.options;
            opts.min = ranges.xaxis.from;
            opts.max = ranges.xaxis.to;
        });
        plot.setupGrid();
        plot.draw();
        plot.clearSelection();

        // don't fire event on the overview to prevent eternal loop

        overview.setSelection(ranges, true);
    });

    $("#overview").bind("plotselected", function (event, ranges) {
        plot.setSelection(ranges);
    });

    // Add the Flot version string to the footer

    $("#footer").prepend("Flot " + $.plot.version + " &ndash; ");
});

AppAsset.php

Код: Выделить всё

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\assets;

use yii\web\AssetBundle;

/**
 * Main application asset bundle.
 *
 * @author Qiang Xue <[email protected]>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
        'css/examples.css'
    ];
    public $js = [
        'js/jquery.flot.js',
        'js/jquery.flot.selection.js',
        'js/jquery.flot.time.js',
        'js/jquery.js',
        'js/js.js'
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Нашла расширение, но мне проще через js, https://www.yiiframework.com/extension/yii2-flot-charts
Может нельзя через js?
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Уже решила расширение, но не выводится

Код: Выделить всё

<?php
use bburim\flot\Chart as Chart;

echo Chart::widget([
    'data' => [
        [
            'label' => 'line',
            'data'  => [
                [1, 1],
                [2,7],
                [3,12],
                [4,32],
                [5,62],
                [6,89],
            ],
            'lines'  => ['show' => true],
            'points' => ['show' => true],
        ],
        [
            'label' => 'bars',
            'data'  => [
                [1,12],
                [2,16],
                [3,89],
                [4,44],
                [5,38],
            ],
            'bars' => ['show' => true],
        ],
    ],
    'options' => [
        'legend' => [
            'position'          => 'nw',
            'show'              => true,
            'margin'            => 10,
            'backgroundOpacity' => 0.5
        ],
    ],
    'htmlOptions' => [
        'style' => 'width:400px;height:400px;'
    ]
]);
?>
composer.json

Код: Выделить всё

{
    "name": "yiisoft/yii2-app-basic",
    "description": "Yii 2 Basic Project Template",
    "keywords": ["yii2", "framework", "basic", "project template"],
    "homepage": "http://www.yiiframework.com/",
    "type": "project",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/yii2/issues?state=open",
        "forum": "http://www.yiiframework.com/forum/",
        "wiki": "http://www.yiiframework.com/wiki/",
        "irc": "irc://irc.freenode.net/yii",
        "source": "https://github.com/yiisoft/yii2"
    },
    "minimum-stability": "*",
    "require": {
        "php": ">=5.4.0",
        "yiisoft/yii2": "~2.0.14",
        "yiisoft/yii2-bootstrap": "~2.0.0",
        "yiisoft/yii2-swiftmailer": "~2.0.0",
        "bburim/flot": "*",
        "conquer/flot": "*"
    },
    "require-dev": {
        "yiisoft/yii2-debug": "~2.0.0",
        "yiisoft/yii2-gii": "~2.0.0",
        "yiisoft/yii2-faker": "~2.0.0",

        "codeception/base": "^2.2.3",
        "codeception/verify": "~0.3.1",
        "codeception/specify": "~0.4.3"
    },
    "config": {
        "process-timeout": 1800,
        "fxp-asset": {
            "enabled": false
        }
    },
    "scripts": {
        "post-install-cmd": [
            "yii\\composer\\Installer::postInstall"
        ],
        "post-create-project-cmd": [
            "yii\\composer\\Installer::postCreateProject",
            "yii\\composer\\Installer::postInstall"
        ]
    },
    "extra": {
        "yii\\composer\\Installer::postCreateProject": {
            "setPermission": [
                {
                    "runtime": "0777",
                    "web/assets": "0777",
                    "yii": "0755"
                }
            ]
        },
        "yii\\composer\\Installer::postInstall": {
            "generateCookieValidationKey": [
                "config/web.php"
            ]
        }
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://asset-packagist.org"
        }
    ]
}
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Переустановила проект basic.
composer.json

Код: Выделить всё

 "minimum-stability": "dev", // минимальная версия
    "require": {
        "php": ">=5.4.0",
        "yiisoft/yii2": "~2.0.14",
        "yiisoft/yii2-bootstrap": "~2.0.0",
        "yiisoft/yii2-swiftmailer": "~2.0.0",
        "conquer/flot": "^1.0@dev", //расширение flot
        "bburim/flot": "dev-master" //расширение flot
    },
Заработало, но мне нужен будет сложный график, вопрос остается актуальным, можно ли обойтись библиотеками js напрямую без установки расширений.
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

В документации написано, что можно библиотеки подключать https://yiiframework.com.ua/ru/doc/guid ... re-assets/
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Итак http://www.flotcharts.org/flot/examples ... index.html - это таблица, которая нужна.
В Yii2 додумалась до такого:

Код: Выделить всё

<?php
use bburim\flot\Chart as Chart;
use bburim\flot\Plugin as Plugin;


echo Chart::widget([ 'data' => [ [ 'label' => 'line', 'data' => [ [1, 1], [2,7], [3,12], [4,32], [5,62], [6,89], ],
    'lines' => ['show' => true], 'points' => ['show' => true], ],
    [ 'label' => 'bars', 'data' => [ [1,12], [2,16], [3,89], [4,44], [5,38], ],
        'bars' => ['show' => true], ], ],
    'options' => [ 'legend' =>
    [ 'position' => 'nw', 'show' => true, 'margin' => 10, 'backgroundOpacity' => 0.5 ], ],
    'htmlOptions' => [ 'style' => 'width:400px;height:400px;' ],
    'plugins' => [
        // Use helper class with constants to specify plugin type
        Plugin::SELECTION,
        Plugin::TIME,
        Plugin::CANVAS
    ]

]);

?>
Как дальше расписать по плагинам, что будет время?
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Или как-то так

Код: Выделить всё


$('#my-chart-id').flot();
urichalex
Сообщения: 994
Зарегистрирован: 2015.08.07, 11:03

Re: flot js и yii2

Сообщение urichalex »

Вам ошибка прямым текстом говорит, что не подходит версия jquery
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Я ее видела- но не знаю как поменять версию query под flot
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Так https://skeeks.com/blog/programming/352 ... i2-proekte
не получается

Код: Выделить всё

 'assetManager' => [
            'linkAssets' => true,
            'appendTimestamp' => true,
            'bundles' => [
                'yii\web\JqueryAsset' => [
                    'sourcePath' => null,   // не опубликовывать комплект
                    'js' => [
                        '//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js',
                     //   YII_ENV_DEV ? 'jquery.js' : 'jquery.min.js'
                    ]
                ],
            ],

        ],
urichalex
Сообщения: 994
Зарегистрирован: 2015.08.07, 11:03

Re: flot js и yii2

Сообщение urichalex »

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4
А вы ей 1.8 подсовываете
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Значит я нашла установленный flot в vendor, когда расширение устанавливала.
вид:

Код: Выделить всё

<?php
$script = <<< JS

$(function() {

var d = [[1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 77], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 676], [1197241200000, 1205], [1197327600000, 906], [1197414000000, 710], [1197500400000, 639], [1197586800000, 540], [1197673200000, 435], [1197759600000, 301], [1197846000000, 575], [1197932400000, 481], [1198018800000, 591], [1198105200000, 608], [1198191600000, 459], [1198278000000, 234], [1198364400000, 1352], [1198450800000, 686], [1198537200000, 279], [1198623600000, 449], [1198710000000, 468], [1198796400000, 392], [1198882800000, 282], [1198969200000, 208], [1199055600000, 229], [1199142000000, 177], [1199228400000, 374], [1199314800000, 436], [1199401200000, 404], [1199487600000, 253], [1199574000000, 218], [1199660400000, 476], [1199746800000, 462], [1199833200000, 448], [1199919600000, 442], [1200006000000, 403], [1200092400000, 204], [1200178800000, 194], [1200265200000, 327], [1200351600000, 374], [1200438000000, 507], [1200524400000, 546], [1200610800000, 482], [1200697200000, 283], [1200783600000, 221], [1200870000000, 483], [1200956400000, 523], [1201042800000, 528], [1201129200000, 483], [1201215600000, 452], [1201302000000, 270], [1201388400000, 222], [1201474800000, 439], [1201561200000, 559], [1201647600000, 521], [1201734000000, 477], [1201820400000, 442], [1201906800000, 252], [1201993200000, 236], [1202079600000, 525], [1202166000000, 477], [1202252400000, 386], [1202338800000, 409], [1202425200000, 408], [1202511600000, 237], [1202598000000, 193], [1202684400000, 357], [1202770800000, 414], [1202857200000, 393], [1202943600000, 353], [1203030000000, 364], [1203116400000, 215], [1203202800000, 214], [1203289200000, 356], [1203375600000, 399], [1203462000000, 334], [1203548400000, 348], [1203634800000, 243], [1203721200000, 126], [1203807600000, 157], [1203894000000, 288]];

// first correct the timestamps - they are recorded as the daily
// midnights in UTC+0100, but Flot always displays dates in UTC
// so we have to add one hour to hit the midnights in the plot

for (var i = 0; i < d.length; ++i) {
d[i][0] += 60 * 60 * 1000;
}

// helper for returning the weekends in a period

function weekendAreas(axes) {

var markings = [],
d = new Date(axes.xaxis.min);

// go to the first Saturday

d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
d.setUTCSeconds(0);
d.setUTCMinutes(0);
d.setUTCHours(0);

var i = d.getTime();

// when we don't set yaxis, the rectangle automatically
// extends to infinity upwards and downwards

do {
markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
i += 7 * 24 * 60 * 60 * 1000;
} while (i < axes.xaxis.max);

return markings;
}

var options = {
xaxis: {
mode: "time",
tickLength: 5
},
selection: {
mode: "x"
},
grid: {
markings: weekendAreas
}
};

var plot = $.plot("#placeholder", [d], options);

var overview = $.plot("#overview", [d], {
series: {
lines: {
show: true,
lineWidth: 1
},
shadowSize: 0
},
xaxis: {
ticks: [],
mode: "time"
},
yaxis: {
ticks: [],
min: 0,
autoscaleMargin: 0.1
},
selection: {
mode: "x"
}
});

// now connect the two

$("#placeholder").bind("plotselected", function (event, ranges) {

// do the zooming
$.each(plot.getXAxes(), function(_, axis) {
var opts = axis.options;
opts.min = ranges.xaxis.from;
opts.max = ranges.xaxis.to;
});
plot.setupGrid();
plot.draw();
plot.clearSelection();

// don't fire event on the overview to prevent eternal loop

overview.setSelection(ranges, true);
});

$("#overview").bind("plotselected", function (event, ranges) {
plot.setSelection(ranges);
});

// Add the Flot version string to the footer

$("#footer").prepend("Flot " + $.plot.version + " &ndash; ");
});


JS;
//маркер конца строки, обязательно сразу, без пробелов и табуляции
$this->registerJs($script, yii\web\View::POS_HEAD);
?>
<div id="header">
    <h2>Visitors</h2>
</div>

<div id="content">

    <div class="demo-container">
        <div id="placeholder" class="demo-placeholder"></div>
    </div>

    <div class="demo-container" style="height:150px;">
        <div id="overview" class="demo-placeholder"></div>
    </div>

    <p>This plot shows visitors per day to the Flot homepage, with weekends colored.</p>

    <p>The smaller plot is linked to the main plot, so it acts as an overview. Try dragging a selection on either plot, and watch the behavior of the other.</p>

</div>

<div id="footer">
    Copyright &copy; 2007 - 2014 IOLA and Ole Laursen
</div>

AppAsset.php

Код: Выделить всё

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\assets;

use yii\web\AssetBundle;

/**
 * Main application asset bundle.
 *
 * @author Qiang Xue <[email protected]>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
        'css/examples.css'

    ];
    public $js = [

      //  'js.js'
    ];
    public $depends = [
        'yii\web\YiiAsset',
       'yii\bootstrap\BootstrapAsset',
    ];
   // public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
    public $jsOptions = array(
        'position' => \yii\web\View::POS_HEAD
    );

}
Ошибки теперь такие:

Код: Выделить всё

yii.js?v=1521657413:520 Uncaught TypeError: window.jQuery is not a function
    at yii.js?v=1521657413:520
(anonymous) @ yii.js?v=1521657413:520
VM46:15 Uncaught ReferenceError: $ is not defined
    at VM46:15
(anonymous) @ VM46:15
bootstrap.js?v=1469461915:8 Uncaught Error: Bootstrap's JavaScript requires jQuery
    at bootstrap.js?v=1469461915:8
(anonymous) @ bootstrap.js?v=1469461915:8
Что за ошибки такие?
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Убрала из web.php

Код: Выделить всё

'assetManager' => [
            'linkAssets' => true,
            'appendTimestamp' => true,
            'bundles' => [
                'yii\web\JqueryAsset' => [
                    'sourcePath' => null,   // не опубликовывать комплект
                    'js' => [
                     //   'https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js',

                     //  YII_ENV_DEV ? 'jquery.js' : 'jquery.min.js'
                    ]
                ],
            ],

        ],
Появились Ошибки

Код: Выделить всё

jquery.js:3860 jQuery.Deferred exception: $.plot is not a function TypeError: $.plot is not a function
    at HTMLDocument.<anonymous> (http://graf/:68:14)
    at mightThrow (http://graf/assets/209908c6/jquery.js:3583:29)
    at process (http://graf/assets/209908c6/jquery.js:3651:12) undefined
jQuery.Deferred.exceptionHook @ jquery.js:3860
process @ jquery.js:3655
setTimeout (async)
(anonymous) @ jquery.js:3689
fire @ jquery.js:3317
fireWith @ jquery.js:3447
fire @ jquery.js:3455
fire @ jquery.js:3317
fireWith @ jquery.js:3447
ready @ jquery.js:3920
completed @ jquery.js:3930
jquery.js:3869 Uncaught TypeError: $.plot is not a function
    at HTMLDocument.<anonymous> ((index):68)
    at mightThrow (jquery.js:3583)
    at process (jquery.js:3651)
(anonymous) @ (index):68
mightThrow @ jquery.js:3583
process @ jquery.js:3651
setTimeout (async)
jQuery.readyException @ jquery.js:3868
(anonymous) @ jquery.js:3888
mightThrow @ jquery.js:3583
process @ jquery.js:3651
setTimeout (async)
(anonymous) @ jquery.js:3689
fire @ jquery.js:3317
fireWith @ jquery.js:3447
fire @ jquery.js:3455
fire @ jquery.js:3317
fireWith @ jquery.js:3447
process @ jquery.js:3671
setTimeout (async)
(anonymous) @ jquery.js:3689
fire @ jquery.js:3317
fireWith @ jquery.js:3447
fire @ jquery.js:3455
fire @ jquery.js:3317
fireWith @ jquery.js:3447
ready @ jquery.js:3920
completed @ jquery.js:3930
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Удалить из vendor расширение flot?
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

$.plot is not a function
https://stackoverflow.com/questions/293 ... a-function
Дают совет использовать http://cdn.jsdelivr.net/jquery.flot/0.8 ... lot.min.js наверно AssetManager имеется в виду
urichalex
Сообщения: 994
Зарегистрирован: 2015.08.07, 11:03

Re: flot js и yii2

Сообщение urichalex »

Вы хоть немного понимаете, задумываетесь над тем, что делаете? Или все методом тыка? Правильные ошибки, ведь вы jquery совсем отключили. Ну и эти ошибки как минимум переводятся на русский, и гуглятся хорошо
urichalex
Сообщения: 994
Зарегистрирован: 2015.08.07, 11:03

Re: flot js и yii2

Сообщение urichalex »

>> $.plot is not a function
Говорит о том, что $.plot - это не функция. Что можно определить как то, что библиотека не подключена или подключена неправильно
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: flot js и yii2

Сообщение svil »

Переустановила проект basic без расширения flot. Заново скопировала библиотеку flot.
Ошибки js

Код: Выделить всё

(index):14 Uncaught ReferenceError: $ is not defined
    at (index):14
(anonymous) @ (index):14
jquery.flot.min.js:7 Uncaught ReferenceError: jQuery is not defined
    at jquery.flot.min.js:7
(anonymous) @ jquery.flot.min.js:7
bootstrap.js?v=1469461915:15 Uncaught Error: Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4
    at bootstrap.js?v=1469461915:15
    at bootstrap.js?v=1469461915:17
(anonymous) @ bootstrap.js?v=1469461915:15
(anonymous) @ bootstrap.js?v=1469461915:17
Вид

Код: Выделить всё

<?php
$script = <<< JS

$(function() {

var d = [[1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 77], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 676], [1197241200000, 1205], [1197327600000, 906], [1197414000000, 710], [1197500400000, 639], [1197586800000, 540], [1197673200000, 435], [1197759600000, 301], [1197846000000, 575], [1197932400000, 481], [1198018800000, 591], [1198105200000, 608], [1198191600000, 459], [1198278000000, 234], [1198364400000, 1352], [1198450800000, 686], [1198537200000, 279], [1198623600000, 449], [1198710000000, 468], [1198796400000, 392], [1198882800000, 282], [1198969200000, 208], [1199055600000, 229], [1199142000000, 177], [1199228400000, 374], [1199314800000, 436], [1199401200000, 404], [1199487600000, 253], [1199574000000, 218], [1199660400000, 476], [1199746800000, 462], [1199833200000, 448], [1199919600000, 442], [1200006000000, 403], [1200092400000, 204], [1200178800000, 194], [1200265200000, 327], [1200351600000, 374], [1200438000000, 507], [1200524400000, 546], [1200610800000, 482], [1200697200000, 283], [1200783600000, 221], [1200870000000, 483], [1200956400000, 523], [1201042800000, 528], [1201129200000, 483], [1201215600000, 452], [1201302000000, 270], [1201388400000, 222], [1201474800000, 439], [1201561200000, 559], [1201647600000, 521], [1201734000000, 477], [1201820400000, 442], [1201906800000, 252], [1201993200000, 236], [1202079600000, 525], [1202166000000, 477], [1202252400000, 386], [1202338800000, 409], [1202425200000, 408], [1202511600000, 237], [1202598000000, 193], [1202684400000, 357], [1202770800000, 414], [1202857200000, 393], [1202943600000, 353], [1203030000000, 364], [1203116400000, 215], [1203202800000, 214], [1203289200000, 356], [1203375600000, 399], [1203462000000, 334], [1203548400000, 348], [1203634800000, 243], [1203721200000, 126], [1203807600000, 157], [1203894000000, 288]];

// first correct the timestamps - they are recorded as the daily
// midnights in UTC+0100, but Flot always displays dates in UTC
// so we have to add one hour to hit the midnights in the plot

for (var i = 0; i < d.length; ++i) {
d[i][0] += 60 * 60 * 1000;
}

// helper for returning the weekends in a period

function weekendAreas(axes) {

var markings = [],
d = new Date(axes.xaxis.min);

// go to the first Saturday

d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
d.setUTCSeconds(0);
d.setUTCMinutes(0);
d.setUTCHours(0);

var i = d.getTime();

// when we don't set yaxis, the rectangle automatically
// extends to infinity upwards and downwards

do {
markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
i += 7 * 24 * 60 * 60 * 1000;
} while (i < axes.xaxis.max);

return markings;
}

var options = {
xaxis: {
mode: "time",
tickLength: 5
},
selection: {
mode: "x"
},
grid: {
markings: weekendAreas
}
};

var plot = $.plot("#placeholder", [d], options);

var overview = $.plot("#overview", [d], {
series: {
lines: {
show: true,
lineWidth: 1
},
shadowSize: 0
},
xaxis: {
ticks: [],
mode: "time"
},
yaxis: {
ticks: [],
min: 0,
autoscaleMargin: 0.1
},
selection: {
mode: "x"
}
});

// now connect the two

$("#placeholder").bind("plotselected", function (event, ranges) {

// do the zooming
$.each(plot.getXAxes(), function(_, axis) {
var opts = axis.options;
opts.min = ranges.xaxis.from;
opts.max = ranges.xaxis.to;
});
plot.setupGrid();
plot.draw();
plot.clearSelection();

// don't fire event on the overview to prevent eternal loop

overview.setSelection(ranges, true);
});

$("#overview").bind("plotselected", function (event, ranges) {
plot.setSelection(ranges);
});

// Add the Flot version string to the footer

$("#footer").prepend("Flot " + $.plot.version + " &ndash; ");
});


JS;
//маркер конца строки, обязательно сразу, без пробелов и табуляции
$this->registerJs($script, yii\web\View::POS_HEAD);

?>
<div id="header">
    <h2>Visitors</h2>
</div>

<div id="content">

    <div class="demo-container">
        <div id="placeholder" class="demo-placeholder"></div>
    </div>

    <div class="demo-container" style="height:150px;">
        <div id="overview" class="demo-placeholder"></div>
    </div>

    <p>This plot shows visitors per day to the Flot homepage, with weekends colored.</p>

    <p>The smaller plot is linked to the main plot, so it acts as an overview. Try dragging a selection on either plot, and watch the behavior of the other.</p>

</div>

<div id="footer">
    Copyright &copy; 2007 - 2014 IOLA and Ole Laursen
</div>
AppAsset.php

Код: Выделить всё

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\assets;

use yii\web\AssetBundle;

/**
 * Main application asset bundle.
 *
 * @author Qiang Xue <[email protected]>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
        'css/examples.css',
    ];
    public $js = [
        'js/jquery.flot.js',
        'js/jquery.flot.time.js',
        'js/jquery.flot.selection.js',
        'js/jquery.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}
web.php

Код: Выделить всё

        'assetManager' => [
            'linkAssets' => true,
            'appendTimestamp' => true,
            'bundles' => [
                'yii\web\JqueryAsset' => [
                    'sourcePath' => null,   // не опубликовывать комплект
                    'js' => [
                        'http://cdn.jsdelivr.net/jquery.flot/0.8.3/jquery.flot.min.js',

                     //  YII_ENV_DEV ? 'jquery.js' : 'jquery.min.js'
                    ]
                ],
            ],

        ],
urichalex
Сообщения: 994
Зарегистрирован: 2015.08.07, 11:03

Re: flot js и yii2

Сообщение urichalex »

Код: Выделить всё

$this->registerJs($script, yii\web\View::POS_HEAD);
На что указыввает yii\web\View::POS_HEAD? На то, что скрипт будет вынесен в <head>
А jquery и flot ваш внизу перед </body>
urichalex
Сообщения: 994
Зарегистрирован: 2015.08.07, 11:03

Re: flot js и yii2

Сообщение urichalex »

Код: Выделить всё

'yii\web\JqueryAsset' => [
                    'sourcePath' => null,   // не опубликовывать комплект
                    'js' => [
                        'http://cdn.jsdelivr.net/jquery.flot/0.8.3/jquery.flot.min.js',

                     //  YII_ENV_DEV ? 'jquery.js' : 'jquery.min.js'
                    ]
                ],
То есть, вы подключили flot ВМЕСТО jquery и хотите чтобы работало?)
Ответить