简体   繁体   中英

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. 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,
  2. Passing the data via an AJAX request after the page is loaded. There are also two ways for this:
    1. Sending a POST request to the same URL,
    2. Sending a request to another 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. I also use Memcache pretty extensively on the server side so my database has less to do.

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. If you own the API it's no big deal because you can adjust your CORS headers, but its something to think about. 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. Just makes life easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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