使用 Laravel 从 php 发送变量到 javascript 的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21712146/
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
Best way to send from php a variable to javascript, using laravel
提问by LuisKx
right now I'm sending a json from laravel to the View and populating a form, the problem is that I need to do certain modifications based in that data from javascript. Right now I use an Ajax request to ask for the exact data from the server, I think thats a little repetitive, and I know I can do something like (var data = {{$data}}) and use it in my js file.
现在我正在从 laravel 向 View 发送一个 json 并填充一个表单,问题是我需要根据来自 javascript 的数据进行某些修改。现在我使用 Ajax 请求从服务器请求确切的数据,我认为这有点重复,我知道我可以做类似 (var data = {{$data}}) 的事情并在我的 js 文件中使用它.
My question is, what is the best solution? Make an ajax call or make the variable directly from the view, I don't know if make the variable from the view is a bad practice or not.
我的问题是,最好的解决方案是什么?进行ajax调用或直接从视图中创建变量,我不知道从视图中创建变量是否是一种不好的做法。
Thanks
谢谢
回答by zainengineer
Here is one solution to pass javascript variables. http://forumsarchive.laravel.io/viewtopic.php?id=2767
这是传递javascript变量的一种解决方案。 http://forumsarchive.laravel.io/viewtopic.php?id=2767
In Controller
在控制器中
// controller
$js_config = array(
'BASE' => URL::base(),
'FACEBOOK_APP' => Config::get('application.facebook_app')
);
return View::make('bla')
->with('js_config', $js_config);
In View
在视图中
<script>
var config = <?php echo json_encode($js_config) ?>;
alert(config.BASE);
alert(config.FACEBOOK_APP.id);
alert(config.FACEBOOK_APP.channel_url);
</script>
Libraries are also available for that purpose
图书馆也可用于此目的
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');
}
There are multiple approaches for this problem
这个问题有多种方法