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?
如果要将对象/值转换为 JSON 字符串,可以使用JSON.stringify
以下方法:
$("#form_attribute").val(JSON.stringify(hash))
这是最新浏览器的内置方法,可将对象转换为表示它的 JSON 表示法。如果某个浏览器不支持它,可以在您的页面上包含几个 polyfill 以提供支持
参考:
JSON.stringify
- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringifywindow.JSON
浏览器兼容性 - http://caniuse.com/json您可以将其存储为 JSON 字符串:
$('#form_attribute').val(JSON.stringify(hash));
或者您可以将原始对象存储在数据属性中:
$('#form_attribute').data('hash', hash);