gpt4 book ai didi

python - Django ajax 格式化约定

转载 作者:太空宇宙 更新时间:2023-11-04 01:43:57 25 4
gpt4 key购买 nike

执行 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");

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

希望对您有所帮助,

马丁

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com