laravel-5将变量传递给JavaScript

时间:2015-05-06 10:27:08

标签: javascript laravel laravel-5

有没有什么方法可以让JavaScript从紧凑型控制器Laravel-5中获取变量。

实施例: 我有以下代码:

   $langs = Language::all();
   return View::make('NAATIMockTest.Admin.Language.index',compact('langs'));

我可以获取此lang并将其传递给JavaScript吗?我已经使用过PHP-Vars-To-Js-Transformer。但是当我在控制器中使用JavaScript :: put两个函数时。它没有用。有什么帮助吗?

这是我的代码,使用PHP-Vars-To-Js-Transformer:

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');

    }

这是我的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']) !!}&nbsp;
                              {!!   Html::linkAction('NAATIMockTest\LanguageController@index', 'Back', null, array('class' => 'btn btn-primary')) !!}
                        </div>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
    </div>
   @endsection

这是我的视图编辑:

 @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: ') !!}&nbsp;{{ $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']) !!}&nbsp;
                            {!! Html::linkAction('NAATIMockTest\LanguageController@index', 'Back', null, array('class' => 'btn btn-primary')) !!}
                        </div>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
   </div>
   @endsection

我在配置文件夹中的javascript.php:

<?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',

];

这个想法是: 我在mysql中有一个表格语言。我想显示下拉列表中有多个属性可供选择,我也想用angularjs进行搜索。这就是我想将变量从控制器传递给JavaScript的原因。另外,我在LanguageController里面有一个名为initLang的函数来检查数据库中是否存在任何语言,在创建视图时它不会显示在下拉列表中。

8 个答案:

答案 0 :(得分:60)

一个有用的例子。

控制器:

public function tableView()
{
    $sites = Site::all();
    return view('main.table', compact('sites'));
}

查看:

<script>    
    var sites = {!! json_encode($sites->toArray()) !!};
</script>

为了防止恶意/意外行为,您可以使用Jon建议的JSON_HEX_TAG链接到此SO answer

的评论
<script>    
    var sites = {!! json_encode($sites->toArray(), JSON_HEX_TAG) !!};
</script>

答案 1 :(得分:13)

标准PHP对象

向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>

还有一个用于解码到JSON的Blade指令。我不确定自哪个版本的Laravel,但在5.5中它可用。使用如下:

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

<强> Jsonable的

使用Laravel对象时,例如CollectionModel您应该使用->toJson()方法。实现\Illuminate\Contracts\Support\Jsonable接口的所有类都支持此方法调用。该呼叫自动返回JSON

<script>
    var collection = {!! $collection->toJson() !!};
    var model = {!! $model->toJson() !!};
</script>

使用Model课程时,您可以在$hidden内定义class属性,这些属性将在JSON中过滤。 $hidden属性,正如其名称所描述的那样,隐藏了敏感内容。所以这种机制对我来说是最好的。这样做如下:

class User extends Model
{
    /* ... */

    protected $hidden = [
        'password', 'ip_address' /* , ... */
    ];

    /* ... */
}

在你看来的某个地方

<script>
    var user = {!! $user->toJson() !!};
</script>

答案 2 :(得分:3)

$langs = Language::all()->toArray();
return View::make('NAATIMockTest.Admin.Language.index', [
    'langs' => $langs
]);

然后在视野中

<script type="text/javascript">
    var langs = {{json_encode($langs)}};
    console.log(langs);
</script>

它不太漂亮

答案 3 :(得分:2)

试试这个 - https://github.com/laracasts/PHP-Vars-To-Js-Transformer 将PHP变量附加到Javascript的简单方法。

答案 4 :(得分:1)

我知道接下来的行没有进行优化,但它是一种快速可读的方式来实现它:

<script>
    var sampleTags = [];
    @foreach ($services as $service)
        sampleTags.push('{{ $service->name }}');
    @endforeach
</script>

修改:抱歉,如果字符串包含特殊字符(例如ó),则必须使用{!! $service->name !!}

答案 5 :(得分:0)

很简单,我使用这段代码:

<强>控制器

$langs = Language::all()->toArray();
return view('NAATIMockTest.Admin.Language.index', compact('langs'));

查看

<script type="text/javascript">
    var langs = <?php echo json_decode($langs); ?>;
    console.log(langs);
</script>

希望它有所帮助,问候!

答案 6 :(得分:0)

对我来说最好的方法是将其放在php刀片中的隐藏div中

<div hidden id="token">{{$token}}</div>

然后在javascript中将其作为常量调用,以避免未定义的var错误

const token = document.querySelector('div[id=token]').textContent

// console.log(token)
// eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MjNlOTcyMi02N2NmLTQ4M2UtYTk4Mi01YmE5YTI0Y2M2MzMiLCJqdGkiOiI2Y2I1ZGRhNzRhZjNhYTkwNzA3ZjMzMDFiYjBiZDUzNTZjNjYxMGUyZWJlNmYzOTI5NzBmMjNjNDdiNjhjY2FiYjI0ZWVmMzYwZmNiZDBmNyIsImlhdCI6IjE2MDgwODMyNTYuNTE2NjE4IiwibmJmIjoiMTYwODA4MzI1Ni41MTY2MjUiLCJleHAiOiIxNjIzODA4MDU2LjMxMTg5NSIsInN1YiI6IjUiLCJzY29wZXMiOlsiYWRtaW4iXX0.GbKZ8CIjt3otzFyE5aZEkNBCtn75ApIfS6QbnD6z0nxDjycknQaQYz2EGems9Z3Qjabe5PA9zL1mVnycCieeQfpLvWL9xDu9hKkIMs006Sznrp8gWy6JK8qX4Xx3GkzWEx8Z7ZZmhsKUgEyRkqnKJ-1BqC2tTiTBqBAO6pK_Pz7H74gV95dsMiys9afPKP5ztW93kwaC-pj4h-vv-GftXXc6XDnUhTppT4qxn1r2Hf7k-NXE_IHq4ZPb20LRXboH0RnbJgq2JA1E3WFX5_a6FeWJvLlLnGGNOT0ocdNZq7nTGWwfocHlv6pH0NFaKa3hLoRh79d5KO_nysPVCDt7jYOMnpiq8ybIbe3oYjlWyk_rdQ9067bnsfxyexQwLC3IJpAH27Az8FQuOQMZg2HJhK8WtWUph5bsYUU0O2uPG8HY9922yTGYwzeMEdAqBss85jdpMNuECtlIFM1Pc4S-0nrCtBE_tNXn8ATDrm6FecdSK8KnnrCOSsZhR04MvTyznqCMAnKtN_vMDpmIAmPd181UanjO_kxR7QIlsEmT_UhM1MBmyfdIEvHkgLgUdUouonjQNvOKwCrrgDkP0hkZQff-iuHPwpL-CUjw7GPa70lp-TIDhfei8T90RkAXte1XKv7ku3sgENHTwPrL9QSrNtdc5MfB9AbUV-tFMJn9T7k

答案 7 :(得分:0)

它很简单而且对我有用...

只需将 PHP 变量传递到单引号中...

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