我一直在试着理解在Django中做Ajax的最佳方式是什么.通过在各处阅读资料,我了解到常见的过程是:
使用大约JavaScript个库(例如jQuery个库)制定Ajax调用,在Django中设置一个URL模式,捕捉调用并将其传递给视图函数
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)
在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!我发现继承支持以这种方式工作要好得多.