开发者

Storing JSON Array in a Hidden HTML element

I have a JSON Array that is defined as follows:

var myItems开发者_StackOverflow社区 = {
  "data": [
    { "id":1, "firstName":"bill", "lastName":"smith" },
    { "id":2, "firstName":"john", "lastName":"apple" },
    { "id":3, "firstName":"will", "lastName":"long"}
  ]
};

I need to store this array in a hidden HTML element so that I can pass it to my server-side code in string format. My problem, I'm not sure how to do this. Can someone tell me how to do this?

Thank you!


Essentially, you want to serialize your array into json, and then specify where you want to store the resulting string value..

document.getElementById('yourHiddenField').value = jsonString;


Use this code:

document.getElementById('input').value = JSON.stringify(myItems);

See here for the JSON documentation:

  • JSON in JavaScript
  • JSON support in ECMAScript 5

NOTE: All moderns browsers provide at least partial support for native JSON parsing (JSON.parse() and JSON.stringify(). Older browsers don't. As suggested by Nick Craver, you can use json2.js for this, and most JavaScript frameworks provide support as well (and most will try to detect the native functions or use their own versions). For instance Dojo's Dojo.toJson() and Dojo.toJson().


What you have is an object literal, not JSON yet...however we can easily convert it to JSON using JSON.stringify(), like this:

document.getElementById("myHiddenInput").value = JSON.stringify(myItems);

To support older browsers without native JSON support (IE <8), include json2.js and the code above will still work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜