Django : View returns JSON content_dictionary, how to decode in Javascript
Let me explain what I'm trying to do, and if someone could point the correct way to do it & a solution to where I'm stuck that would be great !
Someone types url
www.ABC.com/showItem/Blackberry
I lookup "Blackberry" in my database and find data for it, now I want to 开发者_如何学Goshow its details one a page.
Hence in the View I do this
return_data=simplejson.dumps(response_dict)
return render_to_response('workmodule/show_item_details.html', {"item_complete_data": return_data}, context_instance=RequestContext(request))
In myHTML I do this
data_from_django = {{ farm_complete_data }}
Question 1
: Is this the correct method to access the JSON data in the HTML ? Somehow I think there should be a better/cleaner way.
Question 2
: Another problem is all quotes are replaced with """
hence the javscript breaks. If above is the correct way, how to I "decode" the string correctly.
Note :
I have used jquery's .ajax
function earlier and it works great if you are on a page already and making a call to backend. The views in that case have returned the data in the same fashion as above & the data wasn't escaped. Or so it seemed by the time my ajax success: or error: functions handled it.
Thanks for taking time to look at this.
Question 1: that's about right, actually.
Question 2: Don't decode it, pipe it to safe: {{farm_complete_data|safe}} so it doesn't try to html-escape it for you.
Why pass it to a template at all? You just want the JSON, so in the view, do this:
return simplejson.dumps(response_dict)
Then there's no need to worry about encoding/quoting.
精彩评论