简体   繁体   English

如何:在Laravel 4中将数据从控制器传递到JavaScript?

[英]How to: pass data from controller to JavaScript in Laravel 4?

I'm developing a mobile web app with Laravel 4 and jQuery Mobile and I have some problems to pass data from Controller to JavaScript file. 我正在使用Laravel 4和jQuery Mobile开发一个移动Web应用程序,我有一些问题要将数据从Controller传递到JavaScript文件。 I find a solution but I think there is a proper way to do that. 我找到了解决方案,但我认为有一种正确的方法可以做到这一点。

Here is my code: 这是我的代码:

MapController.php MapController.php

class MapController extends BaseController 
{
    public function showMap($id)
    {
        $club = Club::find($id);
        return View::make('pages.map', array('club' => $club));
    }
}

pages/map.php 页/ map.php

<div id="picture" data-role="dialog">
  <div data-role="header" data-theme="d">
    <h1>
      Upload picture
    </h1>
  </div>
  <div data-role="content">
    code here...
  </div>

  <script type="text/javascript">
    var id_club = '<?php echo $club->id ?>';
  </script>
  <script src="public/js/map.js" type="text/javascript">
  </script>
</div>

Does anyone know if there is a better solution to pass data from controller to JavaScript? 有谁知道是否有更好的解决方案将数据从控制器传递到JavaScript?

Use this package https://github.com/laracasts/PHP-Vars-To-Js-Transformer 使用此软件包https://github.com/laracasts/PHP-Vars-To-Js-Transformer

public function index()
{
    JavaScript::put([
        'foo' => 'bar',
        'user' => User::first(),
        'age' => 29
    ]);

    return View::make('hello');
}

HTML HTML

<input type="hidden" id="club-id" value="<?php echo $club->id ?>" />

Javascript 使用Javascript

var club_id = $('#club-id').val().trim();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM