1👍
I don’t understand the usage of View.
Why do you want to pass JSON object as a context value while Template Rendering ?
The standard is When you do a Ajax request its response should be a JSON response i.e mimetype=application/json.
So, You should render the template normally and Convert the result into JSON and return.
e.g:
def ajax(request):
obj = {
'response': render_to_string("2.html", {"a": 1, "b": 2})
}
return HttpResponse(json.dumps(obj), mimetype='application/json')
OR
you can create a JSONResponse class Similar to HttpResponse to make it generic . e.g.
class JSONResponse(HttpResponse):
"""
JSON response
"""
def __init__(self, content, mimetype='application/json', status=None, content_type=None):
super(JSONResponse, self).__init__(
content=json.dumps(content),
mimetype=mimetype,
status=status,
content_type=content_type,
)
and use like : return JSONResponse(obj)
This has been added by default in django 1.7: https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects
Source:stackexchange.com