简体   繁体   中英

What are best practices for exporting variables passed from the server to HTML so that they can be used in javascript modules?

Let's say I'm serving up a web application and my server is passing an object to the front-end that looks like this:

{
   user_name : "Robert",
   user_settings : {/*some settings object*/}
}

If I want to access this information in, say, main.js, in the past I've just made this information global in my html file. (eg):

<html>

    <head>
      <title>Example Page</title>
    <!-- style links would go here -->
    </head>

    <body>

    <!-- script tags would go here -->

        <script>
           window.server_json = {
               user_name : "Robert",
               user_settings : {/*some settings object*/}
           }
        </script>
    </body>
</html>

This really doesn't seem to fit into the way that we're writing javascript these days with webpack and babel. I would like to be able to export that object and use it in other files while avoiding globals.

I'm not sure how to go about this, but I envision it would looks something like:

(Example.html)

<html>

    <head>
      <title>Example Page</title>
    <!-- style links would go here -->
    </head>

    <body>

    <!-- script tags would go here -->

        <script>
           export default json = {
               user_name : "Robert",
               user_settings : {/*some settings object*/}
           }
        </script>
    </body>
</html>

(Main.js)

import json from "./Example.html";
//Do something with the data received from the server

In my current project, I'm using webpack, babel, and vue.js. I've been searching for some way to do this for a few hours now, and would appreciate any help.

EDIT:

To clarify, the data would be sent from the server using PHP and the slim framework. It would look something like this:

$app->get('my/page', function($request, $response){
    return $this->view->render($response, 'my_page.html', [
        "user_name" => "Robert",
        "user_settings" => [/*some settings object*/]
    ]);
});

You can use the vue-resource plugin to request the data from the server. You can use Web Storage API to cache the data on the client.

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