title: How to return JSON data from Flask without ajax
body: <p>Suppose I want to render a page (not just JSON) using Flask with some specific data that I fetch from the database. For example</p>
  
  <p><code>display_data.html</code> includes:</p>
  
  <pre><code>&lt;script src='display_data.js'&gt;&lt;/script&gt;
  ...
  &lt;h1&gt;Data display page!&lt;/h1&gt;
  &lt;div id="chartContainer"&gt;&lt;/div&gt;
  </code></pre>
  
  <p><code>display_data.js</code>:</p>
  
  <pre><code>$(function() {
       draw_chart($("#chartContainer"), json_data); 
       //draw_chart is defined elsewhere and json_data is what I want to pass in
  });
  </code></pre>
  
  <p>Python:</p>
  
  <pre><code>@app.route('/&lt;data_id&gt;')
  def get_display_data_page(data_id):
    data = get_data_by_id(data_id)
    return render_template('display_data.html', data = data)
  </code></pre>
  
  <p>I think that if I want to just "render template", I'd have to include elsewhere in <code>display_data.html</code> the following:</p>
  
  <pre><code>&lt;script&gt;window.json_data = {{ data | tojson | safe}}&lt;/script&gt;
  </code></pre>
  
  <p>This pattern smells bad: I'm leaving an object on the global namespace (so that my JS file can access it), displaying the data as plain text, and rendering a string in that is parsed into JSON so the JS can use it. Looks bad but this does work.</p>
  
  <p>Two other options:</p>
  
  <ol>
  <li><p>Return the data with AJAX. Given the title of this post I'm specifically trying to avoid ajax. The reason for this is mainly that I'm building a mobile site and want to reduce the number of pings back to the server. I'm also thinking (perhaps more metaphysically) about encapsulating the page: once you have it, you have all of it.</p></li>
  <li><p>Render my JS file via Flask and Jinja. This seems like a bummer because I'd have to then write a route down and render the JS based on the same logic that I have in the <code>get_display_data_page</code>: looking up the data by its id, etc. Code duplication and dynamic JS sound like big no-no's to me. </p></li>
  </ol>
  
  <p>Is there a known pattern to doing this well?</p>