简体   繁体   English

在 Django 中将数据传递给 JavaScript 的最佳实践

[英]Best practice for passing data to JavaScript in Django

When writing a view in Django, there are several ways to pass a list of data to javascript.在 Django 中编写视图时,有几种方法可以将数据列表传递给 javascript。 Some of the methods I found are:我发现的一些方法是:

  1. Passing the data in the response text by serializing into JSON and assigning into a JavaScript variable,通过序列化为 JSON 并分配给 JavaScript 变量来传递响应文本中的数据,
  2. Passing the data via an AJAX request after the page is loaded.在页面加载后通过 AJAX 请求传递数据。 There are also two ways for this:也有两种方法:
    1. Sending a POST request to the same URL,向同一个 URL 发送 POST 请求,
    2. Sending a request to another URL向另一个 URL 发送请求

Which method is the most reliable one?哪种方法最可靠?

I think this really comes down to personal preference.我认为这真的归结为个人喜好。 I prefer option 1 because it means the client side has less work to do, which (potentially) can make the page load faster.我更喜欢选项 1,因为这意味着客户端要做的工作更少,这(可能)可以使页面加载速度更快。 I also use Memcache pretty extensively on the server side so my database has less to do.我还在服务器端广泛使用 Memcache,因此我的数据库没有什么可做的。

Of course, whether this matters has a lot to do with what your app is trying to accomplish.当然,这是否重要与您的应用程序试图完成的任务有很大关系。 Mine pulls a good amount of data from the database every time a view is called, so it's beneficial for me to do it this way.每次调用视图时,我的都会从数据库中提取大量数据,因此这样做对我来说是有益的。

Something else to think about is that doing everything server-side avoids having to deal with CORS/CORB issues.还需要考虑的是,在服务器端做所有事情都可以避免处理 CORS/CORB 问题。 If you own the API it's no big deal because you can adjust your CORS headers, but its something to think about.如果您拥有 API,这没什么大不了的,因为您可以调整 CORS 标头,但需要考虑一下。 I've had some difficulties with CORS depending on the APIs I'm trying to interact with and I've made it my policy to never pull from an API on the client side if I can avoid it.根据我尝试与之交互的 API,我在使用 CORS 时遇到了一些困难,并且我的政策是,如果可以避免的话,永远不要从客户端的 API 中提取。 Just makes life easier.只是让生活更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM