最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to: pass data from controller to JavaScript in Laravel 4? - Stack Overflow

programmeradmin2浏览0评论

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. I find a solution but I think there is a proper way to do that.

Here is my code:

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

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

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. I find a solution but I think there is a proper way to do that.

Here is my code:

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

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

Share Improve this question edited Jun 18, 2013 at 18:34 Rubens Mariuzzo 29.2k27 gold badges122 silver badges149 bronze badges asked Jun 18, 2013 at 17:21 bidou88bidou88 6942 gold badges10 silver badges31 bronze badges 1
  • 1 Better way is to request it by AJAX via JSON. Or add hidden input and get it from there. – Stan Commented Jun 18, 2013 at 18:25
Add a comment  | 

2 Answers 2

Reset to default 11

Use this package 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

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

Javascript

var club_id = $('#club-id').val().trim();
发布评论

评论列表(0)

  1. 暂无评论