使用Laravel 4将JSON编码的PHP变量发送到JS

时间:2014-08-08 06:16:26

标签: javascript php jquery json laravel-4

我在将一个JSON编码的php数组传递给Laravel 4中的javascript时遇到了一些麻烦。我将它从我的控制器发送到我的视图,在HTML中填充值字段,然后用JS提取该值。代码如下:

控制器:

$artist_likes_profile = Fanartist::profile_fan_likes(Auth::user()->get()->id);
$artist_likes = json_encode(array("name"=>$artist_likes_profile));

return View::make('artists.show', compact('artist'))
       ->with('artist_likes', $artist_likes);

HTML:

<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="<? php echo $artist_likes ?>">

JS:

var artist_likes = $('#js-helper-artist-likes').val();
console.log(artist_likes);

然而,运行它,我只看到控制台中的artist_likes变量显示为"{"而不是实际的json字符串。

当我添加这两行时(尝试解码js中的json变量):

var artist_likes_decoded = $.parseJSON(artist_likes);
console.log(artist_likes_decoded);

我收到错误:

Uncaught SyntaxError: Unexpected end of input

我知道JSON字符串正在填充值字段,因为我在页面源中看到了这一点:

   <input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{"name":[{"id":215,"fbid":"19538277626","stage_name":"311","city":"","state":"","image_path":"http:\/\/graph.facebook.com\/19538277626\/picture?width=720&height=720",
"description":"311 was formed in 1990 in Omaha, Nebraska."},{"id":18,"fbid":"14591271531","stage_name":"Beck","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/14591271531\/picture?width=720&height=720",
"description":""},{"id":47,"fbid":"137029526330648","stage_name":"Disclosure","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/137029526330648\/picture?width=720&height=720","description":""},
{"id":11,"fbid":"152513780224","stage_name":"Arcade Fire","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/152513780224\/picture?width=720&height=720","description":""}]}">

任何想法我做错了什么?谢谢。

1 个答案:

答案 0 :(得分:1)

这是因为JSON字符串包含配额(&#34;)并且会破坏html解析。你需要先逃脱它们。

<?php echo str_replace('"', '\"', $artist_likes) ?>

替代解决方案是将JSON直接传递给js变量,如果此隐藏输入仅用于为js提供值。

var artists_likes_decoded = <?php echo $artist_likes ?>