I'm using jQuery's $.ajax method to call getjson.php which returns a JSON object using PHPs json_encode($data). The Structure of my JSON looks like this...
[ { "StoreKey": "84", "StoreName": "Region1", "0": "4,055.37", "1": "2,668.29", "2": "4,454.81", "3": "4,789.99", "4": "none", "5": "none", "6": "none", "7": "15,968.46" }, { "StoreKey": "26", "StoreName": "Region2", "0": "2,368.09", "1": "2,270.24", "2": "1,806.76", "3": "1,656.15", "4": "none", "5": "none", "6": "none", "7": "8,101.24" }, { "StoreKey": "Daily", "StoreName": "Totals", "0": "92,614.45", "1": "98,126.78", "2": "104,157.04", "3": "102,581.87", "4": "none", "5": "none", "6": "none", "7": 397480.14 } ]
I can display the JSON object using $('#respo开发者_StackOverflownseDiv').html(result); }); but I would like to parse through through each row using the $.each() method.
When iterating through the JSON object using $.each() only the last JSON object is displayed. This displays the last JSON object -> "7": 397480.14.
var data = $.parseJSON(result);
$.each(data,function(row,store) {
$.each(store,function(key,value) {
$('#responseDiv').html(value);
});
})
The goal is to wrap the JSON objects in < tr > tags for each row and < td > tags for each column for a table/grid look.**
AJAX Request Function.
$.ajax //jQuery Syntax-ajax.api!
({
type: "POST",
url: "includes/getjson.php", //----my php scripts/codes
data: "date="+x,
datatype: "json",
success: function(result)
{
var data = $.parseJSON(result);
$.each(data,function(row,store) {
$.each(store,function(key,value) {
$('#responseDiv').html(value); });
})
}
});
}
It's something I'm not doing or doing incorrectly...
You're replacing the content of #responseDiv each time - you want to append it
$('#responseDiv').html($('#responseDiv').html() + value);
or, shorter:
$('#responseDiv').append(value);
If you're trying to create a table with rows based no the json object, i would recommend using a templating engine like jTemplate or Jquery Template. Then you would simply create a template of your and send your return object to it to render.
<!-- Template content -->
<textarea id="myTemplate" style="display:none">
{#foreach $T as record}
<tr>
<td>{$T.record.StoreKey}</td>
<td>{$T.record.StoreName}</td>
<td>{$T.record.0}</td>
</tr>
{#/for}
</textarea>
Your HTML would be
<table>
<tbody id="placeholder">
</tbody>
</table>
then you would simply send your json result to the templating engine.
$.ajax //jQuery Syntax-ajax.api!
({
type: "POST",
url: "includes/getjson.php", //----my php scripts/codes
data: "date="+x,
datatype: "json",
success: function(result)
{
$("#placeholder").setTemplateElement("myTemplate").processTemplate(result);
}
});
}
精彩评论