python - Django ajax 格式化约定

标签 python django json dom formatting

执行 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 中格式化我的输出?

最佳答案

我一直将 JSON 专门用于 AJAX,使用 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");

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

希望这有帮助,

马丁

关于python - Django ajax 格式化约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1760538/

相关文章:

javascript - 根据索引和重复索引将数组合并为新数组

javascript - 如何将 JSON 对象中的数组从 javascript 传递到 asp.net mvc Controller 方法?

python - 查找名称包含特定字符串的列

python - 更快地调用函数求值

python - SQLAlchemy - MappedCollection 问题

python - 模块未找到错误: No module named 'api'

python - 动态添加属性到 Django 模型

json - "Fatal error: ' EXTERN.h ' file not found"安装 Perl 模块时

python - 与每组中最大值的差值

python - Django - 无法使用信号删除对象更改时的旧文件