Im trying to send a variable from a controller to a JavaScript, I have my controller, and I can send an array:
我试图从控制器发送变量到JavaScript,我有我的控制器,我可以发送一个数组:
public function index()
{
$casa = new Casa(true);
$result = $casa->where(['show'=>true])->get();
return view('casa', array('casa' => $result));
}
If i go to my HTML and I make and echo:
如果我转到我的HTML,我制作并回应:
<html>
<body>
<?php echo $casa ?>
</body>
</html>
I can show my array in the body, I was thinking about make an invisible element and get the array with document.getElementById().innerHTML, but I think this is not the best way.
我可以在体内显示我的数组,我正在考虑创建一个不可见的元素并使用document.getElementById()。innerHTML获取数组,但我认为这不是最好的方法。
Also, I think that I could make an Ajax petition sending a post and get the result, but I dont know if I can get my variable in a simpler way.
此外,我认为我可以发一个Ajax请愿发送帖子并获得结果,但我不知道我是否能以更简单的方式获取我的变量。
I tried to make and echo in Javascript and doesn´t work. some ideas?
我尝试用Javascript制作和回声并且不起作用。一些想法?
Can I have 2 method post to get request in my controller? I already have one to get data from a form, and if I set the Ajax request I will have two post request. I would like have just one.
我可以在控制器中获得2个方法帖子来获取请求吗?我已经有一个从表单中获取数据,如果我设置了Ajax请求,我将有两个发布请求。我想只有一个。
2 个解决方案
#1
2
Jeffrey Way created a package for that. He also made a video explaining it in laracasts.com. The package can be found here: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
Jeffrey Way为此创建了一个包。他还在laracasts.com上制作了一段视频。该软件包可以在这里找到:https://github.com/laracasts/PHP-Vars-To-Js-Transformer
#2
2
You can simply get PHP
variable in JavaScript
like this:
您可以在JavaScript中简单地获取PHP变量,如下所示:
<script>
var casa = '<?php echo $casa ?>';
</script>
you can use alert
to see the result in popup dialog too:
您也可以使用alert来查看弹出对话框中的结果:
<script>
var casa = alert('<?php echo $casa ?>');
</script>
#1
2
Jeffrey Way created a package for that. He also made a video explaining it in laracasts.com. The package can be found here: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
Jeffrey Way为此创建了一个包。他还在laracasts.com上制作了一段视频。该软件包可以在这里找到:https://github.com/laracasts/PHP-Vars-To-Js-Transformer
#2
2
You can simply get PHP
variable in JavaScript
like this:
您可以在JavaScript中简单地获取PHP变量,如下所示:
<script>
var casa = '<?php echo $casa ?>';
</script>
you can use alert
to see the result in popup dialog too:
您也可以使用alert来查看弹出对话框中的结果:
<script>
var casa = alert('<?php echo $casa ?>');
</script>