问题
I need to be able to generate an effectively unlimited number of datasets, so what I want to do is something like this;
<input type="hidden" name="items[]" value="{id:1,name:'some-name'}" />
I tried JSON.stringify to convert my array in javascript and store it in the current hidden input element, but it wraps all the keys and values in double quotes, which obviously conflicts with HTML wrapping the entire value in double quotes. Somehow I need to escape the quotes, but I need this to work two ways...basically these elements are generated with PHP and placed in the page in order, then I can add or delete items on the user end and submit the page, which should have PHP iterating through these hidden elements and updating the records.
Anyone have any suggestions on an escaping method of some sort?
回答1:
You can use escaping function presented here: http://phpjs.org/functions/htmlspecialchars:426
It should escape chars in json and make your string safe to use as value of html attribute.
If you want to do the escaping on PHP then you should use function htmlspecialchars() that is built in PHP.
回答2:
What you want to do is grasp some of html5 data-* attrubites so you can dod
<div id="post-container" data-meta="{id:22,name:'Robert Pitt'}">
..
</div>
Then you can use htmlentites() to make the string safe and use javascript, you can get the data with javascript like so:
function ElementJson(id,attrib)
{
var post_c = document.getElementById(id);
for( var x = 0; x < post_c.attributes.length; x++)
{
if( post_c.attributes[x].nodeName.toLowerCase() == 'data-' + attrib.toLowerCase())
{
return post_c.attributes[x].nodeValue;
}
}
return false;
}
json = ElementJson('post-container','meta');
Via jQuery for instance you can do
json = $('#post-container[data-meta]').attr('data-meta');
A lot of large sites use it especially Facebook
回答3:
base64_encode the data or run it through htmlentities() to turn the quotes in to entities :)
回答4:
To be honest, if you are setting the value in javascript in the page then I am a little surprised that you ran into problems but here are a couple of suggestions: -
Of course the proper thing to do is HTML encode the data in the html attributes - but this requires calling htmlentities or similar so instead, why not URL encode the data using the "built in" javascript encode
and decode
and methods. URL encoding should escape double quotes to '%22'.
Or if you are already using jQuery, use the val()
method to set (and get?) the value - I am sure that would deal with these issues for you (although I have not gone and actually checked this).
来源:https://stackoverflow.com/questions/3145220/store-json-in-a-hidden-input-element