环境说明
Laravel 5.1
jQuery 1.11.3
illuminate/html 5.*
laracasts/utilities ~2.0
安装 PHP-Vars-To-Js-Transformer
-
github网址
https://github.com/laracasts/PHP-Vars-To-Js-Transformer
-
通过Composer安装,修改composer.json
{ "require": { "laracasts/utilities": "~2.0" } }
-
composer更新包
composer update
-
Laravel 增加 service provider
vim config/app.php 修改providers,增加如下内容: Laracasts\Utilities\JavaScript\JavaScriptServiceProvider::class,
-
生成配置文件
php artisan vendor:publish
测试
-
增加路由 vim app/Http/routes.php Route::any(‘test’, function(){
$data = array( 'foo' => 'bar', 'a' => 100, 'array' => array( 'b' => '1111', 'c' => '2222', ), ); JavaScript::put($data); return view('test'); });
-
增加view
vim resources/views/default.blade.php @include('header') @yield('content') @include('footer') vim resources/views/header.blade.php <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>测试</title> <meta name="_token" content="{{ csrf_token() }}"/> </head> <body> vim resources/views/footer.blade.php {!! HTML::script('js/jquery-1.11.3.min.js') !!} {!! HTML::script('js/test.js') !!} </body> </html> vim resources/views/test.blade.php @extends('default') @section('content') @endsection('content')
-
增加js
vim public/js/test.js $(function(){ console.log(foo); console.log(a); console.log(array); });
-
浏览/test查看console的输出