laravel-5 将变量传递给 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30074107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel-5 passing variable to JavaScript
提问by user1610851
is there any ways that JavaScript can get the variable from compact controller Laravel-5.
JavaScript 有什么方法可以从紧凑型控制器 Laravel-5 中获取变量。
Example: I have the code below:
示例:我有以下代码:
$langs = Language::all();
return View::make('NAATIMockTest.Admin.Language.index',compact('langs'));
Can I get this langs and pass it to JavaScript? I already used PHP-Vars-To-Js-Transformer. But when I use JavaScript::put for two functions in the controller. It didn't work. Any help?
我可以得到这个 langs 并将它传递给 JavaScript 吗?我已经使用了 PHP-Vars-To-Js-Transformer。但是当我将 JavaScript::put 用于控制器中的两个函数时。它没有用。有什么帮助吗?
This is my code by using PHP-Vars-To-Js-Transformer:
这是我使用 PHP-Vars-To-Js-Transformer 的代码:
LanguageController: This is my create and edit function :
LanguageController:这是我的创建和编辑功能:
public function create()
{
$names = $this->initLang();
Javascript::put([
'langs' => $names
]);
return View::make('NAATIMockTest.Admin.Language.create',compact('names'));
}
public function edit($id)
{
//
$lang = Language::findOrFail($id);
$names = $this->initLang();
Javascript::put([
'langs' => $names
]);
return View::make('NAATIMockTest.Admin.Language.edit', compact('lang'));
// return View::make('NAATIMockTest.Admin.Language.edit');
}
this is my View create:
这是我的视图创建:
@extends('AdLayout')
@section('content')
< script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('langCtrl', function($scope) {
$scope.languages = langs;
});
</script>
<div class="container-fluid" ng-app="myApp" ng-controller="langCtrl">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Create language
</h2>
</div>
<div class="panel-body">
{!! Form::open() !!}
<p class="text-center">
{!! Form::label('Name','Language: ') !!}
<input type="text" name="searchLanguage" ng-model="searchLanguage">
</p>
<select name="Name[]" multiple size="10" ng-model="lang" ng-click="show()">
<option value="@{{v}}" ng-repeat="(k,v) in languages | filter:searchLanguage">
@{{v}}
</option>
</select><br>
<div class="text-center">
{!! Form::submit('Create',['class'=>'btn btn-primary']) !!}
{!! Html::linkAction('NAATIMockTest\LanguageController@index', 'Back', null, array('class' => 'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
@endsection
This is my View edit:
这是我的视图编辑:
@extends('AdLayout')
@section('content')
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('langCtrl', function($scope) {
$scope.languages = langs;
});
</script>
<div class="container-fluid" ng-app="myApp" ng-controller="langCtrl">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading"><h2>Edit #{{ $lang->id}}</h2></div>
<div class="panel-body">
{!! Form::model($lang) !!}
{!! Form::label('Name','Language: ') !!} {{ $lang->Name }}
<!-- {!! Form::text('Name',null,['disabled']) !!}<br> -->
{!! Form::hidden('id') !!}<input type="text" name="searchLanguage" ng-model="searchLanguage">
</p>
<select name="Name[]" size="10">
<option value="@{{v}}" ng-repeat="(k,v) in languages | filter:searchLanguage">
@{{v}}
</option>
</select><br>
<div class="text-center">
{!! Form::submit('Update',['class'=>'btn btn-info']) !!}
{!! Html::linkAction('NAATIMockTest\LanguageController@index', 'Back', null, array('class' => 'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
@endsection
my javascript.php in config folder:
我的 javascript.php 在 config 文件夹中:
<?php
return [
/*
|--------------------------------------------------------------------------
| View to Bind JavaScript Vars To
|--------------------------------------------------------------------------
|
| Set this value to the name of the view (or partial) that
| you want to prepend all JavaScript variables to.
|
*/
'bind_js_vars_to_this_view' => 'footer',
'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.create',
'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.edit',
/*
|--------------------------------------------------------------------------
| JavaScript Namespace
|--------------------------------------------------------------------------
|
| By default, we'll add variables to the global window object. However,
| it's recommended that you change this to some namespace - anything.
| That way, you can access vars, like "SomeNamespace.someVariable."
|
*/
'js_namespace' => 'window',
];
The idea is: I have a table language in mysql. I want to show the dropdown list with multiple attributes to choose, and I also want to search with angularjs as well. That's why I want to pass the variable from the controller to JavaScript. Additionally, I have the function inside LanguageController called initLang to check if any language is exist inside the database, it isn't displayed inside the dropdown list in create the view.
这个想法是:我在mysql中有一个表语言。我想显示具有多个属性的下拉列表可供选择,我也想使用 angularjs 进行搜索。这就是为什么我想将变量从控制器传递给 JavaScript。此外,我在 LanguageController 中有一个名为 initLang 的函数来检查数据库中是否存在任何语言,它不会显示在创建视图的下拉列表中。
回答by ken
One working example for me.
我的一个工作示例。
Controller:
控制器:
public function tableView()
{
$sites = Site::all();
return view('main.table', compact('sites'));
}
View:
看法:
<script>
var sites = {!! json_encode($sites->toArray()) !!};
</script>
To prevent malicious / unintended behaviour, you can use JSON_HEX_TAGas suggested by Jon in the comment that links to this SO answer
为了防止恶意/意外行为,您可以JSON_HEX_TAG按照 Jon 在链接到此SO 答案的评论中的建议使用
<script>
var sites = {!! json_encode($sites->toArray(), JSON_HEX_TAG) !!};
</script>
回答by algorhythm
Standard PHP objects
标准 PHP 对象
The best way to provide PHP variables to JavaScript is json_encode. When using Blade you can do it like following:
向 JavaScript 提供 PHP 变量的最佳方式是json_encode. 使用 Blade 时,您可以执行以下操作:
<script>
var bool = {!! json_encode($bool) !!};
var int = {!! json_encode($int) !!};
/* ... */
var array = {!! json_encode($array_without_keys) !!};
var object = {!! json_encode($array_with_keys) !!};
var object = {!! json_encode($stdClass) !!};
</script>
There is also a Blade directive for decoding to JSON. I'm not sure since which version of Laravel but in 5.5 it is available. Use it like following:
还有一个 Blade 指令用于解码为JSON. 我不确定从哪个版本的 Laravel 开始,但在 5.5 中它可用。像下面这样使用它:
<script>
var array = @json($array);
</script>
Jsonable's
Jsonable 的
When using Laravel objects e.g. Collectionor Modelyou should use the ->toJson()method. All those classes that implements the \Illuminate\Contracts\Support\Jsonableinterface supports this method call. The call returns automatically JSON.
例如,当使用 Laravel 对象时,Collection或者Model您应该使用该->toJson()方法。所有实现该\Illuminate\Contracts\Support\Jsonable接口的类都支持此方法调用。呼叫自动返回JSON。
<script>
var collection = {!! $collection->toJson() !!};
var model = {!! $model->toJson() !!};
</script>
When using Modelclass you can define the $hiddenproperty inside the classand those will be filtered in JSON. The $hiddenproperty, as its name describs, hides sensitive content. So this mechanism is the best for me. Do it like following:
使用Modelclass 时,您可以在 中定义$hidden属性class,这些属性将在JSON. $hidden正如其名称所述,该属性隐藏了敏感内容。所以这个机制对我来说是最好的。像下面这样做:
class User extends Model
{
/* ... */
protected $hidden = [
'password', 'ip_address' /* , ... */
];
/* ... */
}
And somewhere in your view
在你看来
<script>
var user = {!! $user->toJson() !!};
</script>
回答by PawelW
Try this - https://github.com/laracasts/PHP-Vars-To-Js-TransformerIs simple way to append PHP variables to Javascript.
试试这个 - https://github.com/laracasts/PHP-Vars-To-Js-Transformer是将 PHP 变量附加到 Javascript 的简单方法。
回答by Pawel Bieszczad
$langs = Language::all()->toArray();
return View::make('NAATIMockTest.Admin.Language.index', [
'langs' => $langs
]);
then in view
然后在视图中
<script type="text/javascript">
var langs = {{json_encode($langs)}};
console.log(langs);
</script>
Its not pretty tho
它不漂亮
回答by JCarlosR
Let's say you have a collection named $servicesthat you are passing to the view.
假设您有一个名为$services您要传递给视图的集合。
If you need a JS array with the names, you can iterate over this as follows:
如果您需要一个带有 names 的 JS 数组,您可以按如下方式迭代:
<script>
const myServices = [];
@foreach ($services as $service)
myServices.push('{{ $service->name }}');
@endforeach
</script>
Note: If the string has special characters (like óor HTML code), you can use {!! $service->name !!}.
注意:如果字符串有特殊字符(如ó或 HTML 代码),您可以使用{!! $service->name !!}.
If you need an array of objects(with all of the attributes), you can use:
如果您需要一组对象(具有所有属性),您可以使用:
<script>
const myServices = @json($services);
// ...
</script>
Note: This blade directive @jsonis not available for old Laravel versions. You can achieve the same result using json_encodeas described in other answers.
注意:这个刀片指令@json不适用于旧的 Laravel 版本。您可以使用json_encode其他答案中所述的方法获得相同的结果。
Sometimes you don't need to pass a complete collection to the view, and just an array with 1 attribute. If that's your case, you better use $services = Service::pluck('name');in your Controller.
有时您不需要将完整的集合传递给视图,而只需一个具有 1 个属性的数组。如果这是你的情况,你最好$services = Service::pluck('name');在你的控制器中使用。
回答by Radames E. Hernandez
Is very easy, I use this code:
很简单,我用这个代码:
Controller:
控制器:
$langs = Language::all()->toArray();
return view('NAATIMockTest.Admin.Language.index', compact('langs'));
View:
查看:
<script type="text/javascript">
var langs = <?php echo json_decode($langs); ?>;
console.log(langs);
</script>
hope it has been helpful, regards!
希望它有帮助,问候!

