如何访问AJAX响应返回到模板的Queryset-Django



我想使用ajax将查询集返回到模板。

这是我在一个单独的js文件中的ajax函数:

$(document).ready(function(){
$("#data_to_plot_button").click(function(){
var serialized_data = $("#data_to_plot_form").serialize();

$.ajax({
url: $("data_to_plot_form").data('url'),
data: serialized_data,
type: 'post',
success: function(response){
$("#graph").append('<p>data returned successfuly</p>'); //this line is printed correctly.
$.each(response, function(i, val) {
$('graph').empty().append(
$('<li>').addClass('list-group-item list-group-item-success').text(val)
)
}); // this block adds nothing to the #graph div
}
})
});
});

和我的views.py:

def my_products(request):

queryset_list_intro_products = Intro_products.objects.all().order_by('title') 
products = 0 
if request.method == 'POST':
products_checkbox = request.POST.get('products')
if products_checkbox:
products = serializers.serialize('json', list(queryset_list_intro_products))
context = {
'products': products,
}

return JsonResponse(context, status=200)
return render(request, 'users/basket/my_products.html') 

基于对这个问题的回答,我尝试访问返回的products,它位于response中。但是js代码没有向#graph分区添加任何内容。

在chrome中检查的网络选项卡的XHR部分,ajax调用的状态为200,在预览部分,我可以看到products如下:

产品:"[{"模型":"产品.导入产品","pk":5,"字段":{"products_intro":false,"ip_sensor_intro":false,"control_valve_intro;,"描述":">

descript离子

&"detailed description":""video_link":""is_published":真,";"image_left":""title_left":""description_left":""image_right":""title_right":""description_right":"{},

如何在知道ajax响应是查询集的情况下访问该响应的字段?

您需要做这样的事情;

from django.template.loader import render_to_string
if request.is_ajax():
html = render_to_string(
template_name="your seperate template where you want to display the queryset", 
context=dict_of_items_to_be_passed_to_above_temp.
)
data_dict = {"html_from_view": html}
return JsonResponse(data=data_dict, safe=False)