如何:在 Laravel 4 中将数据从控制器传递到 JavaScript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17175079/
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
How to: pass data from controller to JavaScript in Laravel 4?
提问by bidou88
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.
我正在使用 Laravel 4 和 jQuery Mobile 开发移动 Web 应用程序,但在将数据从 Controller 传递到 JavaScript 文件时遇到了一些问题。我找到了解决方案,但我认为有一种正确的方法可以做到这一点。
Here is my code:
这是我的代码:
MapController.php
地图控制器.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?
采纳答案by Stan
HTML
HTML
<input type="hidden" id="club-id" value="<?php echo $club->id ?>" />
Javascript
Javascript
var club_id = $('#club-id').val().trim();
回答by RamiroRS
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');
}