Django Json回应

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.

Since Django 1.7, there is a JsonResponse class that takes a Python object in parameter and returns the correct HttpResponse.

from django.http import JsonResponse
sub_categories = SubCategory.objects.filter(parent_category=id)
return JsonResponse(sub_categories, safe=False)  # Without safe flag, sub_catgeories should be a dict