I am using this array( as an example)
http://pastebin.com/M0ZJgAVsi am using json_encode() on it and fetching it using javascript
does anyone care to tell me
to get the num rows would i simply use
var numrows = json['numrows'];
and to loop over each row would i use
for(row in json['rows']) {
}
and then inside that to get to each datapoint would i just use
for(data 开发者_开发百科in row) {
}
or am i completely off track?
If you receive the deserialized JSON data in the JavaScript as an object json
, then the code could looks like following
var rows = json.rows; // cache json.rows array in a variable for better performance
for (var iRow=0, cRows = rows.length; iRow<cRows; iRow++) {
var row = rows[iRow];
for (var iData=0, cData = row.length; iData<cData; iData++) {
var data = row[iData];
// do something with the data like
// alert(data);
}
}
In general you receive typically JSON data in deserialized form as an object (if you use jQuery.ajax
for example). So the access of the data in JavaScript is very simple. It is just accessing of the fields of the object or accessing of the elements of the array. For performance purpose only it is better to use always an indexed loop as a "for in"
loop (see http://www.jslint.com/lint.html#forin). If you access a property of an object (like the property rows
) it is always better to use dotted notation (json.rows
) as an index notation (json[rows]
). And the last recommendation is caching property value in a local variable (like var row=rows[iRow]
or var cRows = rows.length
) always if you access the property more as one time.
You can find interesting information from http://jquery-howto.blogspot.com/2009/06/javascript-for-loop-vs-jquery-each.html about the more effective way to enumerate data in the array (read also the last version of the suggested loop in the comment).
It is also a good idea to verify your JavaScript code in JSLint (see http://www.jslint.com/).
Yes, you're at correct point.
for(row in json['rows']) {
for(data in row) {
document.write(data);
}
}
for(row in json['rows']) {
for(entry in json['rows'][row]) {
document.write(json['rows'][row][entry]);
}
}
精彩评论