Directly create JSON data in JS and traverse and use it. js creates json data.

Source: Internet
Author: User

Directly create JSON data in JS and traverse and use it. js creates json data.

Previously, I have already talked about returning json data to the foreground in the background and traversing json data in the foreground.

Here we will talk about directly creating JSON data in JS and then traversing and using ~

The creation code is as follows: (The JSON object is created)

var YearSelect = {}; var Year = 2014; var DateOption; for (var i = Year; i < Year + 12; i++) { DateOption = {'Year':i, 'Month':i-Year+1}; / alert(DateOption.Year) YearSelect[i] = DateOption; }

Create a JSON object, including the year and month data.

Why do I create a JSON object? I am familiar with JSON objects. The php background also returns a json object.

The json object does not have the length attribute ~~

Therefore, the traversal should be:

for(var key in YearSelect){ alert(YearSelect[key].Year); alert(YearSelect[key].Month); }

In this way, you can ~

Remember to distinguish between json objects and arrays ~ Otherwise it will always be undenfined


Js traverses json object read data

Var jsondata = yourdata;
For (var x in jsondata ){
Document. write (x + "=" + jsondata [x]);
}
If jsonarray is used, set a layer of.
Var jsonarray = yourarray;
For (var I = 0; I <jsonarray. length; I ++ ){
Var jsonobj = jsonarray [I];
For (var x in jsonobj ){
Document. write (x + "=" + jsonobj [x]);
}
}

How to traverse the json data transmitted in the background in js

$ (Document). ready (function (){
Var data = "{root: [{limCode: 'ygmk1 '}, {limCode: 'ygzz2'}, {limCode: 'ygzj2'}, {limCode: 'yzj1'}]} ";
Var datajson = eval ("(" + data + ")");
$. Each (datajson. root, function (I, item ){
Alert ("limCode:" + item. limCode );
});
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.