Reputation: 37924
I am pretty sure, i am messing up this.
I do ajax request to get some informations of an object.
$.ajax({
url: "/get_obj_ajax/",
type: "get",
data: {id:id}
}).done(function(data){
if(data!='bad'){
data = data.split('°');
var objtitle = data[0];
var objcontent = data[1];
..
});
and in django views:
def get_obj_ajax(request):
if request.method == "GET":
obj= MyModel.objects.get(id=int(request.GET.get('id')))
data = obj.title + '°' + obj.content
return HttpResponse(data)
return HttpResponse('bad')
this is what I normally do. but today while I was eating my lunch, I thought, there must be some more professional approach for this.. because i feel like this is too dumb code. and if suddenly content
of my obj has something with °
in it, the parsing goes wrong.
.. any guidance will be appreciated.
Upvotes: 1
Views: 64
Reputation: 21740
you can return json data
:
def get_obj_ajax(request):
import json
data={"issuccess": 'no'}
if request.method == "GET":
obj= MyModel.objects.get(id=int(request.GET.get('id')))
data = {"issuccess": 'yes',"title":obj.title ,"content": obj.content}
return HttpResponse(json.dumps(data), content_type="application/json")
in templates:
if(data.issuccess == 'yes'){
var objtitle = data.title;
var objcontent = data.content;
}...
Upvotes: 1