简体   繁体   中英

AJAX - Django - better approach?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM