繁体   English   中英

将从服务器传递的变量导出到HTML以便可以在javascript模块中使用的最佳做法是什么?

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

假设我正在提供一个Web应用程序,而我的服务器正在将一个对象传递给前端,如下所示:

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

如果我想在例如main.js中访问此信息,过去我只是在html文件中将此信息设置为全局信息。 (例如):

<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>

这似乎与我们如今使用webpack和babel编写javascript的方式似乎并不匹配。 我希望能够导出该对象并在其他文件中使用它,同时避免使用全局变量。

我不确定该怎么做,但我想它看起来像这样:

(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

在当前项目中,我正在使用webpack,babel和vue.js。 几个小时以来,我一直在寻找某种方法来完成此操作,希望能对您有所帮助。

编辑:

为了明确起见,将使用PHP和slim框架从服务器发送数据。 它看起来像这样:

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

您可以使用vue-resource插件从服务器请求数据。 您可以使用Web Storage API在客户端上缓存数据。

暂无
暂无

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

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