在django视图中使用HttpResponse时如何访问模板中的json对象? [英] How to access json objects in the template when HttpResponse is used in django view?

查看:17
本文介绍了在django视图中使用HttpResponse时如何访问模板中的json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将 id 发送到我的 django 视图并从服务器获取几个 json 对象,这是有效的,但我无法使用模板中的响应对象,即 json 对象,但只有一个具有上下文的对象仅在我的 http 服务成功函数中命名.

I have below code that sends id to my django view and gets couple of json objects from the server, this is working but I couldn't use the response objects in the template i.e., json objects but only one object with the context names only in my http service success function.

这是查看代码 -

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 中使用它.

When I keep breakpoint in the view while returning HttpResponse, I can see the objects with the data that am expecting, however I am not sure how to make use of it in the javascript inside template.

当我使用 render_to_response 方法时,我可以使用如下的响应上下文,例如 -

When I use render_to_response method, I could use the response context as below for example -

jdata_wc = {{ wc_V_json|safe }};

当我从视图中使用 HttpResponse 返回数据时,如何在我的模板中使用相同的方式?

How can I use the same way in my template when I return the data using HttpResponse from the view ?

推荐答案

首先,您的 Django 代码存在一些问题.不涉及模板,因此将某些东西称为上下文"或使用 mark_safe 是没有意义的.此外,您只需将 某些 变量转换为 JSON.需要把整条数据当成一个,一口气转成JSON:

Firstly,there are some problems with your Django code. There is no template involved, so it makes no sense to call something "context", or to use mark_safe. Also you only convert some of your variables to JSON. You need to treat the whole piece of data as one, and convert it to JSON in one go:

data = {
    'jobseekers': basic_v_obj,
    'jobseekers_wc': wc_v_obj,
    'wc_V_json': wc_v_json_list
}
return HttpResponse(json.dumps(data), content_type="application/json")

然后,客户端存在问题.JSON.stringify 用于将 JS 数据转换为 JSON,而不是相反.你需要 JSON.parse.并且您在转换之前尝试访问原始 JSON 数据,就好像它是一个 JS 对象一样.

Then, there are issues on the client side. JSON.stringify is for converting JS data to JSON, not the other way round. You need JSON.parse. And you are attempting to access the raw JSON data as if it were a JS object, before you convert it.

success(function (data) {
     if (data == "null") {
         alert('server returned nothing but success');
     } else {
         data = JSON.parse(data);
         jdata = data['wc_V_json'];     
         alert('First Sk: ' + JSON.stringify(jdata));
     }
});

这篇关于在django视图中使用HttpResponse时如何访问模板中的json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆