doz22551
2015-10-31 16:10
浏览 470
已采纳

从laravel控制器获取php变量到javascript

Im trying to send a variable from a controller to a JavaScript, I have my controller, and I can send an array:

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

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.

I tried to make and echo in Javascript and doesn´t work. some ideas?

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.

图片转代码服务由CSDN问答提供 功能建议

我试图将变量从控制器发送到JavaScript,我有我的控制器,我可以发送一个数组 :

  public function index()
 {
 
 $ casa = new Casa(true); 
 
 $ result = $ casa-&gt;其中(  [ '节目'=&GT;真]) - &GT;得到();  
返回视图('casa',数组('casa'=&gt; $ result)); 
} 
   
 
 

如果我转到我的HTML和我 make和echo:

 &lt; html&gt; 
&lt; body&gt; 
&lt;?php echo $ casa?&gt; 
&lt; / body&gt;  
&lt; / html&gt; 
   
 
 

我可以在正文中显示我的数组,我正在考虑制作一个不可见的元素并使用document.getElementById()获取数组 .innerHTML,但我认为这不是最好的方法。

另外,我认为我可以发一个Ajax请愿发送帖子并获得结果,但我不知道我是否能以更简单的方式获取我的变量。

我尝试在Javascript中制作和回显并且不起作用。 一些想法?

我可以在控制器中获得2个方法帖子来获取请求吗? 我已经有一个从表单中获取数据,如果我设置了Ajax请求,我将有两个发布请求。 我想只有一个。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doupeng8419 2015-10-31 18:50
    已采纳

    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

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题