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 );
});
});