最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Get JSON data stored in a hidden input element? - Stack Overflow

programmeradmin1浏览0评论

I'm building a website that store json data to hidden input element with php

<input type='hidden' class='json_data' name='json_data' value='".json_encode($data[0])."'>

with that code, I have this result:

<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">

but when I try to get the value with jquery.val and trying to show ALBUM_ID, i get this {

anything wrong with my way of putting json into html correctly?

and then get it with jquery / javascript ?

thanks

I'm building a website that store json data to hidden input element with php

<input type='hidden' class='json_data' name='json_data' value='".json_encode($data[0])."'>

with that code, I have this result:

<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">

but when I try to get the value with jquery.val and trying to show ALBUM_ID, i get this {

anything wrong with my way of putting json into html correctly?

and then get it with jquery / javascript ?

thanks

Share Improve this question asked Aug 29, 2013 at 13:05 yosafatadeyosafatade 1851 gold badge2 silver badges12 bronze badges 4
  • 3 May be because of " inside " – Moazzam Khan Commented Aug 29, 2013 at 13:06
  • i did htmlspecialchars but still get the same result. – yosafatade Commented Aug 29, 2013 at 13:17
  • Why are you putting this in an hidden input and not just adding a script tag to the page with the value? – epascarello Commented Aug 29, 2013 at 13:23
  • because the data will be save to the database. – yosafatade Commented Aug 29, 2013 at 13:35
Add a ment  | 

4 Answers 4

Reset to default 3

First go ahead at this open console and see the result. Ctl+Shift+j.

http://jsfiddle/techsin/Q2MHA/

You need to do two things fix. ' and "'

Second just this code

JSON.parse($('.json_data').val())[0]

you need [0] because for some reason your json object is wrapped in []..you would know why.

Your html should look like this

<input ... value='[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]'...>

You need to correctly handle entities in your input's value. If you populate it with PHP, use htmlspechalchars() and use result from this function

inspect the following line carefully.

<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">

As you see you have used " for your string enclosement. The json string also includes " which breaks your string enclosement. Use ' to enclose the string.

<input class="json_data" type="hidden" value='[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]' name="json_data">

Try to escape the " with addslashes or htmlspecialchars

or encode the string with base64 and decode it with JS before parsing the string as JSON

发布评论

评论列表(0)

  1. 暂无评论