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

javascript - Storing JSON Array in a Hidden HTML element - Stack Overflow

programmeradmin0浏览0评论

I have a JSON Array that is defined as follows:

var myItems = {
  "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!

I have a JSON Array that is defined as follows:

var myItems = {
  "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!

Share Improve this question asked Dec 7, 2010 at 12:45 VillagerVillager 6,68922 gold badges67 silver badges87 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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)

  1. 暂无评论