Django Json回应 [英] Django Json Response

查看:222
本文介绍了Django Json回应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要一些帮助,我正在使用Ajax方法来加载网站中的某些内容:



这是我的方法:

  def get_subcat(request,id):
sub_categories = SubCategory.objects.filter(parent_category = id)
return HttpResponse(sub_categories )

这是ajax方法:

  function menu_element_hover(id){
$ .ajax({
url:'/ catalog / get_subcat /'+ id
})。done (数据){
alert(data);
})。fail(function(error){
alert('error');
});

}



问题是,我需要一个Json回复,但是我所得到的是一个带有子类别的String加入的例子:SnorkelsShirts



如果有人可以帮助我,请D:不好意识! / p>

解决方案

  sub_categories = SubCategory.objects.filter(parent_category = id)

返回查询集,如果将其返回为HttpResponse,则会尝试将其强制为人类可读的东西,如字符串。 p>

如果你想要返回json,那么首先你需要做一些像

  from django.utils import simplejson 
return HttpResponse(simplejson.dumps(sub_categories))

但是那么你会碰到下一个问题,因为查询不是json可序列化的。总而言之,您需要做的是将json格式的内容序列化,如果要在浏览器/服务器之间移动json,因为HttpResponse是不是一些神奇的课程,可以猜到你想要什么,只是这样做。


I just need some help, I'm making an Ajax method to load some content in the site:

this is my method:

def get_subcat(request, id):
sub_categories = SubCategory.objects.filter(parent_category=id)
return HttpResponse(sub_categories)

this is the ajax method:

function menu_element_hover(id){
$.ajax({
    url:'/catalog/get_subcat/'+id
}).done(function(data){
    alert(data);
}).fail(function(error){
    alert('error');
});

}

The problem is, that I need a Json response, but all I get is a String with the sub-categories joined example: SnorkelsShirts

if someone can help me please :D, ill appreciate!

解决方案

sub_categories = SubCategory.objects.filter(parent_category=id)

Returns queryset and if you return it as HttpResponse, then it tries to coerce them into something human readable - like string.

If you want to return json, then first you need to do something like

from django.utils import simplejson
return HttpResponse(simplejson.dumps(sub_categories))

But then you will run into next problem as queryset is not json serializeable.

All in all, what you need to do is to take care of serializing the content to json format, if you want to move json between browser/server, since HttpResponse is not some magical class, that can guess what you want and just do it.

这篇关于Django Json回应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆