I use $.getJSON to get data from .json file. My .json file's structure looks like the one below
data.json
{
"foo" : {
"foo1" : {
"prop1": "foo1's prop1",
"prop2": "foo1's prop2",
"prop2": "foo1's prop3",
},
...
},
"bar" : {
"bar1" : {
"prop1": "bar1's prop1",
"prop2": "bar1's prop2",
"prop2": "bar1's prop3",
},
...
},
...
}
and my HTML structure
<div class="container">
<div class="container_header">Choose</div>
<a href="#" class="container_a" id="foo">Foo</a>
<a href="#" class="container_a" id="bar">Bar</a>
...
</div>
<div class="second_container">
<div class="container_header">Choose</div>
<div id="get_json">
</div>
</div>
and .js file that include $.getJSON
$(document).ready(function() {
var $bolumler = $('#get_json');
$(".container_a").click(function(event){
var $a_id = $(this).attr('id');
$.getJSON('data.json', function(data) {
$bolumler.html('');
$bolumler.fadeOut(300, function() {
if ($a_id == "foo") {
$.each(data.foo,function(i,data2) {
$bolumler.append("<a href='#'>"+data2.prop1+"</a>");
});
} else if ($a_id == "bar") {
...// lots of else if
}
});
$bolumler.fadeIn(300);
});
});
});
I want to get data from data.json according to clicked a's id.
For example, if i click first a -which has id foo- i want to get foo1,foo2... then i want to use their prop1,pro2,... values. I make it possible with lots of else if statemennt but that was long. Is it possible to use $.each(variable,function(){});
. I tried these -hopelessly- but they didn't work.
$.each(data.$bk,function(i,data2) {
var newData = data+"."+$bk;
$.each(newData,function(i,data2) {
You can use this to get objects as you want..
data["foo"]
or in your case
data[$a_id]
you can do this also in the $.each