How to write json in the page?

  node.js, question

Recently I saw a page of UC and found that although it is SPA, the first screen is loaded very fast. After looking at the source code, I found that it should write the JSON data of the first screen on the page inside, so I don’t have to make ajax request for the first time.

view-source:http://qiqu.uc.cn/?  uc_param_str=frpfvedncpssntnwbiprmi#!  /index/index

clipboard.png

I don’t know how to realize this. I spent half a day using Express and didn’t get it out.

The code on the node side looks like this.

var express = require('express');
 var router = express.Router();
 
 /* GET home page. */
 router.get('/', function(req, res, next) {
 var context = {
 title: 'My New Post',
 body: 'This is my first post!'
 };
 res.render('index', {data: JSON.stringify(context)});
 });
 
 module.exports = router;

Code for client:

<!DOCTYPE html>
<html>
      <head>
        <META http-equiv=Content-Type content="text/html; charset=utf-8">
        <title>Document</title>
        <script src="http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js"></script>
        <script src="http://cdn.bootcss.com/handlebars.js/4.0.5/handlebars.min.js"></script>
      </head>
    <body>
        <div id="content"></div>
        <script id="entry-template" type="text/x-handlebars-template">
          <div class="entry">
            <h1>{{title}}</h1>
            <div class="body">
              {{body}}
            </div>
          </div>
        </script>
        <script>
            var json = '{{data}}'.replace(/&quot;/g, '"');
            var data = JSON.parse(json);
            console.log(data); //此处可正常输出数据
            var source   = $("#entry-template").html();
            var template = Handlebars.compile(source);
            var html = template(data);
            console.log(html); //此处可以打印出模板,但是数据为空
            $('#content').innerHTML = html;
        </script>
    </body>
</html>

I didn’t quite understand what you were trying to say, the page was used.requireJSDo asynchronous loading, as for writing json is not a.JSON.stringifyWell


You may want to do this (a guess is not necessarily right
node

var express = require('express');
 var router = express.Router();
 
 router.get('/', function(req, res, next) {
 var context = {
 title: 'My New Post',
 body: 'This is my first post!'
 };
 res.render('index', {data: JSON.stringify(context)});
 
 });
 
 module.exports = router;

Front end

<div id="content"></div>
 <script id="data" type="text/x-handlebars-template">{{{data}}}</script>
 <script id="entry-template" type="text/x-handlebars-template">
 <div class="entry">
 <h1>\{{title}}</h1>
 <div class="body">
 \{{body}}
 </div>
 </div>
 </script>
 <script>
 var data=JSON.parse($('#data').html())
 var source   = $("#entry-template").html();
 var template = Handlebars.compile(source);
 var html = template(data);
 $('#content').html(html);
 </script>