I am trying to append my JSON data to a div. For some reason I am not seeing, it does not appen开发者_开发百科d. The data is collected correctly from Django view, I can see this is the FireBug console.
Here is my JS
$.getJSON('/chat/xhr_test/', function(response_array) {
var arr = response_array;
$.each(arr, function(count, item) {
var messageList = (this.pk + ' ' +this.nickname +': '+ this.message +'<br>');
$("#chatbox").append(messageList);
});
});
You can't use "this" when you have function variables in your each statement. remove count and item, then you can use "this" or rather use item[count]
var messageList = (item[count].pk + ' ' +item[count].nickname +': '+ item[count].message +'<br>');
Let's debug
$.getJSON('/chat/xhr_test/', function(response_array) {
var arr = response_array;
console.dir(arr);//is this an array?
var chatbox=$('#chatbox');//cache the chatbox -- ideally this should be placed outside getJSON for reuse
console.log('chatbox length', chatbox.length);//does chatbox exist?
if (chatbox.length){
$.each(arr, function(count, item) {
console.log(count, item);//getting an integer and an object?
var messageList = (item.pk + ' ' +item.nickname +': '+ item.message +'<br />');
console.log(messageList);//look good?
chatbox.append(messageList);//append to the cached chatbox element
});
});
}
});
Once you make sure your variables are set up the way you think they are, things fall into place.
$.each might require you to specify .items
instead of passing the whole variable:
$.each(arr.items, function(count, item) {
精彩评论