Skip to main content
 首页 » 编程设计

python之Django ajax 格式化约定

2024年09月03日37lidabo

执行 ajax 请求的正确方法是什么,我看到人们使用返回的 render_to_string 以便他们可以使用模板语言在 python 中完成所有格式设置。比如~

return render_to_string('calendar.html', { 
'self' : self, 
'month' : self.today.month,}) 

以此作为 javascript:

$('#django_calendar_response').html(response) 

但我也看到有人使用诸如

之类的 dom 函数在 javascript 中格式化他们的输出
return HttpResponse(serializers.serialize("json", 
ilst, relations=('user',)), "application/json") 

javascript在哪里

items_display=function(items){ 
    return LI(null, 
    A({'class':'userlink', 
    'href':'/url/user/'+items.fields.user.fields.name}, 
    items.fields.user.fields.name), 

其中一个是正确的,另一个是错误的吗?我应该用 javascript 还是在 python 中格式化我的输出?

请您参考如下方法:

我一直专门为 AJAX 使用 JSON,使用 simplejson 返回任何数据真的很简单,它看起来像这样:

from django.utils import simplejson 
reply = simplejson.dumps({'comment_body': formatted_post, 'user_icon': request.user.profile.image.url }) 
return HttpResponse(reply, mimetype="application/json") 

在客户端,使用 jquery 的 .post 方法处理 json 回复也非常简单,您可以指定 json 作为您的数据类型:

$.post("/postcomment/", { body: comment_body }, 
  function(data){ 
    alert(data.comment_body) 
  }, "json"); 

我并不是说这是最好的解决方案,但事实证明它非常强大且易于处理...

希望对您有所帮助,

马丁