0

I was wondering what the best option would be for doing ajax calls to update a list of usernames. I can either

a. do a ajax call and get the user object back and build the html and append it into a div

build_html = function(obj) {
    html = 'username - ' + obj.username
    $('#container').append(html);
}

b. do a ajax call and have the django return back the html.

response = render_to_response ('user_item_template.html', {'user' : user})
return response._container

If the response is successful I then append this to the container div.

Are there any cons to doing it with method 'b' because depending on the situation building html in javascript can have problems such as unescaped characters and it's just messy in general.

Thanks

mirugai
  • 175
  • 4
  • 12

2 Answers2

7

If you're requesting something that will solely be used for generating HTML, then just return the HTML as the response. No need to involve the client, and your server will invariably be faster at the generation, especially if caching is employed.

If you need data from a response, i.e. stuff you can introspect later to make decisions in your JS, then you need to return JSON and handle the generation of any HTML client side.

Basically, if you can get by with returning flat HTML, do it.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

I'd say it depends... In most cases (especially if you care about mobile users with slow(er) connections) transferring less data is more important than the time spent parsing the JSON and generating the HTML client-side.

Recommended read: http://ryanflorence.com/2012/client-v-server-templating/

Dan F.
  • 1,353
  • 16
  • 23