parsing specific values in JSON for ajax
I was given this code earlier but am having a hard time parsing the correct data.
I have the following JSON
{
flavors: [{
"image": "images/bbtv.jpg",
"desc": "BioBusiness.TV",
"id": "1"
}, {
"image": "images/grow.jpg",
"desc": "Grow Staffing",
"id": "2"
}]
}
and I want to only show id:1 or id:2.
I have the following code for Ajax
$.ajax({
type: "POST",
url: "foodservice/all.js",
dataType: "json",
cache: false,
data: {"flavors": filterId(flavors, 'a')},
contentType: "application/json",
success: function(data) {
$('#flav开发者_JS百科or-detail').html("<div/>");
$.each(data.flavors, function(i,item){
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});
and the following function to filter through the JSON object
function filterId(obj, filteredId) {
var resultObj = $.extend({},obj);
for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].id && obj[i].id !== filteredId ) {
delete obj[i];
}
}
}
return resultObj;
}
However, this code does not return anything. Can someone tell me what I am missing?
Im pretty new to JSON, Ajax so any help would be greatly appreciated.
Thanks!
Why not just check in the "each" code?
$.each(data.flavors, function(i,item){
if (item.id > 2) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
I changed the following code to make it filterable
$.ajax({
type: "GET",
url: "foodservice/all.js",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$('#flavor-detail').html("<div/>");
$.each(data.flavors, function(i, item) {
if (item.id != flavorid) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});
and for each link to change the output,
$('#amare').click(function() {
flavorid = "1";
});
$('#sec').click(function() {
flavorid = "2";
})
精彩评论