ExpressJS Pass variables to JavaScript

后端 未结 5 1355
谎友^
谎友^ 2021-02-07 12:35

I am completely lost on this; I am using NodeJS to fetch a JSON and I need to pass the variable to my page and have JavaScript use the data.

app.get(\'/test\', f         


        
相关标签:
5条回答
  • 2021-02-07 13:07

    Try the following:

    alert('!{myVar}')
    

    It's a good idea to JSON encode the data if is more than just a string.

    alert('!{JSON.stringify(myVar)}')
    
    0 讨论(0)
  • 2021-02-07 13:11

    As Timothy said:

    <script type="text/javascript>var myVar = #{JSON.stringify(myVar)};</script>
    

    This can also be done as follows in if you don't like to write HTML in jade templates:

    script
      var myVar = !{JSON.stringify(myVar)};
      var myVar2 = !{JSON.stringify(myVar2)};
    

    Update: For Express 4 use script. instead of script so that it will be rendered as javascript instead of html.

    0 讨论(0)
  • 2021-02-07 13:17

    Well, Javascript (and V8) has a built in function to render JSON from a object, and JSON happens to be syntactially compatible with Javascript.

    So the easiest way to do what your trying to do would be:

    <script type="text/javascript>var myVar = #{JSON.stringify(myVar)};</script>
    

    And, yes, you can use HTML in a Jade template.

    0 讨论(0)
  • 2021-02-07 13:23

    I know I'm a bit late to the party, but I actually wrote a module (JShare) a few months ago to solve this exact problem. Check it out: https://npmjs.org/package/jshare

    0 讨论(0)
  • 2021-02-07 13:27

    You could leverage Now.js for this. It easily allows you to share variables client/server side real-time.

    Check it out: http://www.nowjs.com/

    0 讨论(0)
提交回复
热议问题