How to access json objects in the template when HttpResponse is used in django view?

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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.

Here is the view 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") 

Here is the http service function using AngularJS:

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

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.

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

jdata_wc = {{ wc_V_json|safe }}; 

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

回答1:

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") 

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!