【问题标题】:Pass server variable into client side script将服务器变量传递到客户端脚本
【发布时间】:2018-04-01 02:28:18
【问题描述】:

我正在运行一个快速应用程序,使用 EJS 作为我的模板引擎。 但是我在将变量从我的服务器传递到我的客户端脚本时遇到了困难。

我已尝试使用 JSON.stringify 和 JSON.parse,正如其他 stackoverflow 问题中所建议的那样。

服务器端代码:

       .post(function (req, res) { //Is there a better way to update votes than using post request?
        if (req.body.buttoncolor === 'red') {
            Dilemma.findByIdAndUpdate(dilemmaID, {
                $inc: {
                    red_dilemma_votes: 1
                }
            }, function (err, dilemma) {
                if (err) {
                    console.log('Error updating votes on dilemma in root: ' + err);
                } else {

                    res.render('index', {
                        dilemma: dilemma,
                        buttonclicked: JSON.stringify('red')
                    })

                    console.log(JSON.stringify('red'));
                    console.log('Data from post request in root: ' + dilemma);

                }
            });

        }

客户端代码:

<%
if (typeof(buttonclicked) !== "undefined" && buttonclicked){

%>

    <script>
        var buttonclicked = JSON.parse(<%= buttonclicked %>);
        console.log('buttonclicked in script: ' + buttonclicked);
        showResults(<%= buttonclicked %>);

    </script>


    <%}  

%>

客户是这样解释的:

    <script>
        var buttonclicked = JSON.parse(&#34;red&#34;);
        console.log('buttonclicked in script: ' + buttonclicked);
        showResults(&#34;red&#34;);

    </script>

【问题讨论】:

    标签: json node.js parsing variables express


    【解决方案1】:

    根据docs:

    • &lt;%= 将值输出到模板中(HTML 转义)
    • &lt;%- 将未转义的值输出到模板中

    所以你必须在模板中使用&lt;%-而不是&lt;%=来输出未转义的数据。

    <%
    if (typeof(buttonclicked) !== "undefined" && buttonclicked){
    
    %>
    
        <script>
            var buttonclicked = JSON.parse("<%- buttonclicked %>");
            console.log('buttonclicked in script: ' + buttonclicked);
            showResults("<%- buttonclicked %>");
    
        </script>
    
    
        <%}  
    
    %>
    

    【讨论】:

    • 是的,对不起。之后我立即删除了它,因为它实际上并没有修复它。它解决了一系列问题中的第一个问题 :) 仍然难以解析变量。
    • 哦,那么祝你好运解决这些问题。不过,我个人在您的代码中看不到任何其他问题。
    • 谢谢 :) 我收到了这个errorhere。使用此代码:client & server
    • 哦,是的,现在我明白了。服务器上是String,而客户端上是Object。虽然我使用 &lt;%- 的建议是正确的,但您也应该在客户端将 json 用引号括起来。我猜这应该可行。将编辑我的答案。
    • 或者你甚至可以一开始就省略JSON.parse,哈哈。就var x = &lt;%- x %&gt;;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多