【发布时间】:2016-04-19 17:41:36
【问题描述】:
我有以下代码将 id 发送到我的 django 视图并从服务器获取几个 json 对象,这是有效的,但我无法使用模板中的响应对象,即 json 对象,但只有一个具有上下文的对象名称仅在我的 http 服务成功函数中。
这是查看代码-
def preview(request):
if request.method == "POST":
response_data = {}
try:
data=json.loads(request.body.decode())
v_pid=data["id"]
basic_v_obj = tsbasicinfo.objects.get(emailid = request.session.get('emailid'))
if tswex.objects.filter(pid = v_pid).exists():
wc_v_obj = tswex.objects.filter(pid=v_pid)
wc_v_qs = tswex.objects.filter(pid=v_pid)
wc_v_json_list = [obj.as_dict() for obj in wc_v_qs]
else:
wc_v_obj =''
wc_v_json_list=''
context = {
'js': basic_v_obj,
'jjs':wc_v_obj,
}
context['wc_V_json'] = mark_safe(json.dumps(wc_v_json_list, ensure_ascii=False))
except:
context = {'status': "nodata"}
return HttpResponse(context, content_type="application/json")
这里是使用AngularJS的http服务函数:
$scope.preview_ang = function (clicked_id) {
$http({
method: 'POST',
url: 'pvcan',
data: {
'id': clicked_id
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function (data) {
if (data == "null") {
alert('server returned nothing but success');
} else {
alert(JSON.stringify(data,null,2));
jdata = data['wc_V_json'];
alert('First Sk: '+JSON.stringify(jdata)); // displays unknown.. as data is just a string object containing context names :(
}
})
.error(function (data, status, headers, config) {
alert('server returned error :'+status);
})
}
当我在返回 HttpResponse 时在视图中保留断点时,我可以看到带有预期数据的对象,但是我不确定如何在模板内的 javascript 中使用它。
当我使用 render_to_response 方法时,我可以使用如下的响应上下文 -
jdata_wc = {{ wc_V_json|safe }};
当我使用 HttpResponse 从视图返回数据时,如何在模板中使用相同的方式?
【问题讨论】:
标签: angularjs django django-templates