# view code:
response_data = []
for p in product:
response_record = {}
response_record['pname'] = p.name
response_data.append(response_record) ...
# make json type array end
return HttpResponse(json.dumps(response_data, default=date_handler,
sort_keys=True), "application/json")
例如,我想在ajax响应中获取 response.product.pname 等值:
# expected json output:
{
["product": {"pname": 'a', "pid": '2'}]
}
答案 0 :(得分:0)
我终于找到了选择
查看:
def search(request):
if request.method == 'POST' and request.is_ajax():
value = request.POST.get('value')
products = product.objects.filter(p_name__icontains=u'%s' % value)#Convert to unicode
#make json type array begin
response_data = []
final_response = {}
for p in product:
response_record = {}
response_record['pname'] = p.name
response_record['pid'] = p.id
response_data.append(response_record)
final_response["product"] = response_data
#make json type array end
return HttpResponse(json.dumps(final_response, default=date_handler, sort_keys=True), "application/json")
else:
return HttpResponse("Bad Request Detected!! :(")
JS:
$.ajax({
type: 'POST',
url: '/Search/',
data:{value:val},
dataType: "json",
success:function(response)
{
$.each(response.product, function (i, val)
{
alert(val.pname+" "+val.pid);
}
);
}