简体   繁体   中英

Access server-side javascript variable for manipulation with client side javascript

Using sails.js as a framework for a node.js app I'm building.

I'm trying to retrieve information previously set by a user (ie settings for my app) from the back end, and then use these settings in my client-side javascript.

I currently have a controller which retrieves the information from the database and passes it to the view where it will be needed.

return res.view('dashboard', { configs: configurations });

I know it is accessible when rendering html, but don't know how to pass it to the javascript environment running on the browser.

Any tips would be amazing!

To clarify, I'm not trying to render this information in the html page (ie the method of using <%= variable %> , I want to use it in the javascript running on the page.

If i understood your question correctly; you can use the server side variable in your script tag.

<script>

    var something = <%= serversideVariable %>;

    var  <%= serversideVariable %> = "some value";

</script>

This would work as javascript.

You can generate something like this in your view. During page loading this script will be executed and any following script will have access to GlobalSettings .

<script type="text/javascript">
var GlobalSettings = 
{
    //.. JSON with parameters for client
}
</script>

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