admin管理员组

文章数量:1326140

Say I have a hash and I want to enter it as a val()

$("#form_attribute").val( hash )

It gets stored as a string "[Object, object]"

How do I keep it as a hash and then allow the form to send this hash to my server?

Say I have a hash and I want to enter it as a val()

$("#form_attribute").val( hash )

It gets stored as a string "[Object, object]"

How do I keep it as a hash and then allow the form to send this hash to my server?

Share Improve this question asked Dec 10, 2012 at 19:22 TripTrip 27.1k48 gold badges162 silver badges281 bronze badges 3
  • I'm pretty sure you'd have to serialize it, before storing it in the input element. – BenM Commented Dec 10, 2012 at 19:24
  • Is hash an object of some sort, or is it an actual string? If it an object, you could try the JSON.stringify method to convert the object to a string. On the server, you will have to turn it back into an object. – Kyle Commented Dec 10, 2012 at 19:24
  • By "hash" you mean "object"? Please show us what exactly you have there. – Bergi Commented Dec 10, 2012 at 19:24
Add a ment  | 

2 Answers 2

Reset to default 9

If you want to convert an object/value to a JSON string, you could use JSON.stringify to do something like this:

$("#form_attribute").val(JSON.stringify(hash))

This is a built-in method to most recent browsers that converts an object to JSON notation representing it. If a certain browser doesn't support it, there are several polyfills to include on your page to provide support


References:

  • JSON.stringify - https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
  • window.JSON browser patibility - http://caniuse./json
  • JSON3 polyfill - http://bestiejs.github./json3/
  • JSON2 polyfill - https://github./douglascrockford/JSON-js
  • JSON2 vs JSON3 - JSON polyfill: JSON 2 or JSON 3?

You can store it as a JSON string:

$('#form_attribute').val(JSON.stringify(hash));

Or you can store your original object in a data attribute:

$('#form_attribute').data('hash', hash);

本文标签: javascriptHow do I store a hash into a form inputStack Overflow