douzhaocheng4533 2014-08-07 05:21
浏览 21

将JSON编码的PHP变量发送给JS

I am trying to send a PHP variable to my javascript. In order to do this, I encode the php variable with json, send it to my view with my controller, use it as a value in a hidden html form, and then pull the value with js, using parseJSON to get the final product.

HTML (I'm using laravel, the brackets are equivalent to php tags):

<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{{$artist_likes}}">

JS

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

In the page source, I see that the value is populating with the json string, but when I print it to the console from my js like the above, all that is showing is: [{

I am not sure why this is.

I want to perform:

var artist_likes_decoded = $.parseJSON(artist_likes);

to get the decoded variable in JS, but this is impossible without the encoded string coming up correctly in the artist_likes variable in js.

Any ideas what I'm doing wrong? Thank you.

  • 写回答

3条回答 默认 最新

  • donglu7816 2014-08-07 05:28
    关注
    <input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{{ echo $artist_likes}}">
    
    评论

报告相同问题?