我一直在试着理解在Django中做Ajax的最佳方式是什么.通过在各处阅读资料,我了解到常见的过程是:

  1. 使用大约JavaScript个库(例如jQuery个库)制定Ajax调用,在Django中设置一个URL模式,捕捉调用并将其传递给视图函数

  2. in the Python view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or simplejson)

  3. 在JavaScript中定义一个回调函数,用于接收JSON数据并对其进行解析,以便创建需要显示的任何HTML.最后,JavaScript脚本将HTML放在它应该停留的地方.

Now, what I still don't get is how are Django templates related to all of this? Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...

The only resource I found that goes in this direction is this snippet (769) but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.

Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?

非常感谢!

UPDATE: please use 100 because it is an enhanced version of the one above!我发现继承支持以这种方式工作要好得多.

推荐答案

Hey thanks vikingosegundo!

I like using decorators too :-). But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead the snippet n. 942 cause it's an improved version of the original one. Here's how it works:

假设您有一个任意大小的模板(例如,‘subtemplate.html’),其中包含一个您可以重用的有用挡路:

     ........
    <div id="results">          
        {% block results %}
            {% for el in items %}
                   <li>{{el|capfirst}}</li>
            {% endfor %}
        {% endblock %}      
    </div><br />
     ........

通过在视图文件中导入上面的代码段,可以轻松引用模板中的任何块.一个很酷的特性是,模板之间的继承关系被考虑在内,所以如果你引用了一个包含另一个块的块,诸如此类,一切都应该正常工作.因此,ajax视图如下所示:

from django.template import loader
# downloaded from djangosnippets.com[942]
from my_project.snippets.template import render_block_to_string

def ajax_view(request):
    # some random context
    context = Context({'items': range(100)})
    # passing the template_name + block_name + context
    return_str = render_block_to_string('standard/subtemplate.html', 'results', context)
    return HttpResponse(return_str)

Json相关问答推荐

使用SQL查询从SON中查找第n个密钥对值

使用单元和非单元版本反序列化Rust中的枚举,而无需编写自定义反序列化程序

写入JSON文件的流

迭代powershell双维json对象

如何使用jolt将嵌套数据变成线性数据

JOLT 获取带有动态键的数组

如何在 Postman 中匹配 json 响应中的内容?并可视化

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

在PowerShell中按时间戳过滤JSON

JSON 模式验证

Spring MVC 4:application/json内容类型设置不正确

如何获取json格式的KendoGrid显示数据?

如何通过 NSJSONSerialization 在 JSON 中包含空值?

带有方法参数的 WCF webHttpBinding 错误. 最多可以在没有包装元素的情况下序列化一个主体参数

Swift :将 struct 转换为 JSON?

请求返回字节,我无法解码它们

将 json 转换为 C# 数组?

FastAPI:如何将正文读取为任何有效的 json?

为什么 RestTemplate 不将响应表示绑定到 PagedResources?

我如何反序列化以杰克逊为单位的时间戳?