Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django ajax格式约定_Python_Django_Json_Dom_Formatting - Fatal编程技术网

Python Django ajax格式约定

Python Django ajax格式约定,python,django,json,dom,formatting,Python,Django,Json,Dom,Formatting,做ajax请求的正确方法是什么?我见过有人使用返回的render_to_字符串,以便他们可以使用模板语言在python中进行所有格式化。乙二醇~ return render_to_string('calendar.html', { 'self' : self, 'month' : self.today.month,}) 将此作为javascript: $('#django_calendar_response').html(response) 但我也看到有人使用dom函数在javascript

做ajax请求的正确方法是什么?我见过有人使用返回的render_to_字符串,以便他们可以使用模板语言在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");
我并不是说这是最好的解决方案,但它被证明是非常健壮和易于处理的

希望这有帮助


马丁

我两者都做。有时我在大页面模板中有一些短模板片段。渲染这些内容并返回html以插入DOM(因为代码已经设置好)通常比编写JS(再次)更枯燥。其他时候,我只是生成一些JSON并将其注入DOM


很快,您就可以根据情况混合搭配。

正确吗?这取决于AJAX的期望。通常Ajax使用JSON。您的AJAX使用的是什么?这是可以预料的,我只是不确定除了在javascript中保持对象可供操作或在python中格式化所有内容的可靠性之外,这两种方法是否有优点/缺点