Javascript 如何访问AJAX响应返回到模板的Queryset-Django
我想使用ajax将查询集返回到模板 这是一个单独的js文件中的ajax函数:Javascript 如何访问AJAX响应返回到模板的Queryset-Django,javascript,jquery,django,ajax,django-templates,Javascript,Jquery,Django,Ajax,Django Templates,我想使用ajax将查询集返回到模板 这是一个单独的js文件中的ajax函数: $(document).ready(function(){ $("#data_to_plot_button").click(function(){ var serialized_data = $("#data_to_plot_form").serialize(); $.ajax({ url: $("
$(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
}
})
});
});
基于对这一问题的回答,我尝试访问作为响应的返回产品。但是js代码没有向graph div添加任何内容
在chrome中inspects的网络选项卡的XHR部分,ajax调用的状态为200,在预览部分,我可以看到如下产品:
产品:[{型号:products.intro_产品,主键:5,字段:{产品介绍:假,ip传感器介绍:假,控制阀介绍:假,水质传感器介绍:假,附件介绍:真,封面介绍:照片/产品/简介封面/解决方案.png,标题:附件,副标题:,描述:描述,详细描述:,视频链接:,是否发布:真,图片左:,标题左:,描述iption_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)
django 3.1中不支持request.is_ajax吗?以及如何在ajax方法的成功函数中使用js文件中的html?我使用相同的东西进行搜索。这很好。并且数据目录也可以在js中用于解析数据。嗨,你错过了$'graph'。@Swati感谢你的朋友,但它没有帮助!显示你例外的输出。还有,json您添加了问题中的is console result?即:console.logresponse?
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)