I am calling this JSON file:
{
"data" : [
{
"type" : "file",
"target" : "TheGreatest.doc",
"workspace" : "Huddle Workspace One",
"user" : "Chan Marshall"
},
{
"type" : "comment",
"target" : "martes.mp3",
"workspace" : "Huddle Workspace One",
"user" : "Fernando Corona"
},
{
"type" : "file",
"target" : "Papalon.pdf",
"workspace" : "Huddle Workspace Two",
"user" : "Tom Jenkinson"
},
{
"type" : "whiteboard",
"target" : "My Manic & I",
"workspace" : "Huddle Workspace One",
"user" : "Laura Marling"
}
],
"error" : false,
"code" : 200
}
With jQuery AJAX on click of a link:
$('#content > .section > h2 > a').live('click',function() {
$('#content > .section > ul').toggle();
/*
JSON
*/
var $jsonURL = 'response.json';
$.ajax({
type: 'GET',
url: $jsonURL,
dataType: "json",
success: function(data){
var $html = '';
$.each(data.data, function(i, data){
if (data.type == 'file') {
var $string = 'workspace';
} else if (data.type == 'comment') {
var $string = 'file';
} else {
var $string = 'workspace';
}
$html += '<li class="' + data.type + '">';
$html += '<strong>New ' + data.type + '</strong> was added to the ' + $string + ' ';
$html += '<a href="' + data.target + '">' + data.target + '</a> ';
$html += '<a href="' + data.workspace + '">' + data.workspace + '</a>';
$html += ' by <a href="#">' + data.user + '</a>';
$html += '</li>';
$('#content > .section > ul').append($html);
});
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
Whereas i was expecting to append 4 new list elements it brings back 10.
Any ideas as to where i am going wrong?
The scope of your $html variable should be managed so that it is “set to first item” with a
+not a+=on the FIRST action within the .each loop – as you are appending it within the loop this then “resets” it for each element, you need to set it to start of the element first within that loop.I also notice that this:
could be more simply: