如何使用jquery遍历带有对象的数组



我已经练习纯Django(没有js的django(一段时间了。因此,我决定更进一步,将Jquery Ajax包含在我的django中。我可以在哪里将一些数据动态插入到我的 html 中。

然而,问题是使用 jquery ajax 循环遍历 django 模型响应对我不起作用。 下面是我的jquery。有人使用 jquery 帮助完成数组。

function ajaxLoad(item){
$.ajax({
type:  'POST',
url :   '../ajax/fetch_category/',
data: {
'parameter':item
},
cache:false,
dataType: 'json',
success: function(response_data) {
//This is an example of respone data i get from ajax , though was created manually
var data = [
{
"model": "gallery.photogallery",
"pk": 2,
"fields": 
{
"title": "This is my title", 
"picture_choices": "Urban", 
"description": "This is my good description .",
"user": 2, 
"date_posted": "2018-06-13T20:13:57.774Z",
"views": 3,
"likes": 2, 
"country": "AG",
"slug": "this-is-my-title"
}
}
];
//here am looping through the array
for( item in data){
console.log(item);
$.each(item, function( key, value ) {
console.log( key + ": " + value );
});
}

},
error: function(XMLHttpRequest,textStatus,errorThrown) {
console.log("XMLHttpRequest", XMLHttpRequest);
console.log("textStatus", textStatus);
console.log("errorThrown", errorThrown); 
}
});
}

jQuery 中ajax方法的dataType参数设置您期望从服务器返回的数据类型。您已将其设置为"text",这意味着jQuery将响应视为纯文本。这没有用,特别是当您想将其视为对象并循环访问其键时。

虽然你没有展示你的观点,这本来是有用的,但我认为你实际上是在发送 JSON。在这种情况下,您应该将该参数设置为"json"- 或者完全省略它,在这种情况下,jQuery 将做出明智的猜测。

你从 Django 得到什么取决于你在视图中返回的内容。 使用render()快捷方式,您将获得一个 HttpResponse 对象。

对于 Ajax,我倾向于返回 JsonResponse 对象。

如果返回纯查询集,则必须先通过序列化程序传递它们。

最新更新