通过Django模板标记渲染JSON对象 [英] Render JSON objects through Django template-tag
问题描述
目前的解决方案是在jQuery中乏味地构造html:
$。ajax({
url:url,
type:POST,
success: function(data){
var obj = $ .parseJSON(data);
$ .each(obj,function(){
data = this ['fields'];
post + =< p id ='+ this ['pk'] +'>+ data ['creator'] + data ['created'] + data ['body'];
post + =depth:+ data ['depth'];
post + =< a name ='+ this ['pk'] +'class ='show_answers'href ='+ show_url +'>显示< / a>;
post + =< a name ='+ this ['pk'] +'href ='+ answer_url + '>答案< / a>< / p>;
post + =< div id ='+ this ['pk'] +_div'>< / div>;
});
$('# + div_id)html的(后);
},
跨域:假
});
Templatetags是服务器端,所以不,你不能使用Django的模板来处理Ajax请求的结果 - 而不是直接最少。可能的解决方案:
-
您最终可以写,将采取你的JSON数据并返回的HTML格式的视图,但是这将是沉重的一面了一下。
-
如果JSON是来自自己的应用程序,你可以返回一个HTML片段,而不是JSON。
-
如果json来自另一个网站,您还可以在应用程序中查看请求,并从json返回一个格式化的html片段(然后你最后,如果你的应用程序在ajax / json的东西很沉重,你可能想使用一些js模板框架或者像angular.js
I receive a dictionary of Django objects in a JSON format via AJAX in the template. Is there any possibility to render this dictionary through a Django template-tag? Can I call a Django template-tag from jQuery and transfer the object as a parameter to it?
The current solution is to tediously construct the html in jQuery:
$.ajax({
url: url,
type: "POST",
success: function(data) {
var obj = $.parseJSON(data);
$.each(obj, function() {
data = this['fields'];
post += "<p id='" + this['pk'] + "'>" + data['creator'] + data['created'] + data['body'];
post += "depth: " + data['depth'];
post += "<a name='" + this['pk'] + "' class='show_answers' href='" + show_url + "'>Show</a>";
post += "<a name='" + this['pk'] + "' href='" + answer_url + "'>Answer</a></p>";
post += "<div id='" + this['pk'] + "_div'></div>";
});
$('#' + div_id).html(post);
},
crossDomain: false
});
Templatetags are server-side, so no, you cannot use django's templating to handle the result of an Ajax request - not directly at least. Possible solutions :
you can eventually write a view that would take your json data and returns formatted html, but that's going to be a bit on the heavy side.
if the json comes from your own application, you could return an html fragment instead of json.
if the json comes from another site, you could also have a view in your app doing the request and returning a formatted html fragment from the json (then you'd post to this view).
finally if you're app is heavy on ajax/json stuff, you may want to use some js templating framework or something like angular.js
这篇关于通过Django模板标记渲染JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!