【问题标题】:How to access json objects in the template when HttpResponse is used in django view?在django视图中使用HttpResponse时如何访问模板中的json对象?
【发布时间】: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


    【解决方案1】:

    首先,您的 Django 代码存在一些问题。不涉及模板,因此调用“上下文”或使用mark_safe 是没有意义的。此外,您只需将 一些 变量转换为 JSON。您需要将整条数据视为一个数据,并一次性将其转换为 JSON:

    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 对象一样。

    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));
         }
    });
    

    【讨论】:

    • 非常感谢丹尼尔!
    猜你喜欢
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2017-09-28
    • 2020-07-05
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多