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

后端 未结 1 956
心在旅途
心在旅途 2021-01-26 12:57

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.,

1条回答
  •  一生所求
    2021-01-26 13:21

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

    0 讨论(0)
提交回复
热议问题