php - jQuery Looping JSON Data
I have created APIs to retrieve data from my server and then I get the data with json format like this :
{
"items": [
{
"2013-03-28": 1771,
"2013-03-29": 1585,
"2013-03-30": 1582,
"2013-03-31": 1476,
"2013-04-01": 2070,
"2013-04-02": 2058,
"2013-04-03": 1981,
"2013-04-04": 1857,
"2013-04-05": 1806,
"2013-04-06": 1677,
"2013-04-07": 1654,
"2013-04-08": 2192,
"2013-04-09": 2028,
"2013-04-10": 1974,
"2013-04-11": 1954,
"2013-04-12": 1813,
"2013-04-13": 1503,
"2013-04-14": 1454,
"2013-04-15": 1957,
"2013-04-16": 1395
}
]
}
How do I looping with my json data dynamically using jQuery? My code :
<html>
<head></head>
<body>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type : "GET",
url: "myurl.php",
cache: false,
dataType: "jsonp",
success:function(data){
if(data==''){
alert('Fail');
}else{
alert('Success');
}
}
})
});
</script>
</body>
</html>
How do I modify my jQuery to get data dynamically following the date that the data will change every day as in the example I wrote above data?? Thanks before...
Answer
Solution:
There are a few things to consider with your example data, but in your case, the following will do the trick:
Here is a working example
But what does all this mean?...
First of all, we need to get the object that we want to work with, this is the list of dates/numbers found between a
{ }
(which means an object) - an array is defined as[ ]
. With the example given, this is achieved like so:because
items
is an array, and the object we want is the first item in that array.Then we can use the foreach technique, which effectively iterates all properties of an object. In this example, the properties are the date values:
Because we are iterating the properties,
item
will be the property value (i.e. the date bit), so item is the date value:Finally we get the number part. We can access the value of any given object property by using the string value of the property index (relative to the object), like so:
If you already know which date you want the value for, then you can access it directly like so:
Answer
Solution:
Using loop through the
items
Answer
Solution:
You can use the jQuery each function to do this. For example like this:
Where
k
is the key andv
is the value of the item currently processed.Answer
Solution:
//get your detail info.
var detail = data.items[0];
$.each(detail, function(key, val) {
}