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

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

问题描述

下面我有code发送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.

这里认为code -

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

当我把断点在视图中,而返回的Htt presponse,我可以看到与我预期的数据的对象,但我不知道如何在内部模板中的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 }};

我如何使用我的模板以同样的方式,当我回用的Htt presponse从视图中的数据?

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

推荐答案

首先,有一些问题,你的Django code。有没有涉及到的模板,所以它是没有意义的东西叫背景,或者使用 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));
     }
});

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

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