I am populating divs with json but I don’t think I am doing it the best way. Seems like alot of code and some it seems like it could share.
//data for DOM
$.getJSON('json/device.json', function (data) {
var items = [];
$.each(data[0].attributes, function (key, val) {
items.push('<li id="' + key + '">' + ' ' + val + '</li>');
});
$('<ol/>', {
'class': 'raw-list',
html: items.join('')
}).hide().fadeIn().appendTo('.json');
});
$.getJSON('json/device.json', function (data) {
var items = [];
$.each(data[0].status, function (key, val) {
items.push(val);
});
$('<span/>', {
'class': 'sort-label error',
html: items.join('')
}).hide().fadeIn().appendTo('.status-input .sort-label');
});
$.getJSON('json/device.json', function (data) {
var items = [];
$.each(data[0].location, function (key, val) {
items.push(val);
});
$('<span/>', {
'class': 'sort-label',
html: items.join('')
}).hide().fadeIn().appendTo('.location-input .sort-label');
});
$.getJSON('json/device.json', function (data) {
var items = [];
$.each(data[0].type, function (key, val) {
items.push(val);
});
$('<span/>', {
'class': 'sort-label',
html: items.join('')
}).hide().fadeIn().appendTo('.type-input .sort-label');
});
$.getJSON('json/device.json', function (data) {
var items = [];
$.each(data[0].brand, function (key, val) {
items.push(val);
});
$('<span/>', {
'class': 'sort-label',
html: items.join('')
}).hide().fadeIn().appendTo('.brand-input .sort-label');
});
You don’t need multiple
$.getJSONcalls if you’re retrieving the same data every time.For example:
Since you’re using a similar block of code for the display logic of most of the data sets, you could wrap this into a function:
And then call it by: