【问题标题】:Serverside send information to vanilla HTML服务器端将信息发送到普通 HTML
【发布时间】:2020-03-31 14:17:36
【问题描述】:

是否可以像使用 Pug 或 EJS 一样从服务器端向客户端发送信息,但没有视图引擎?

现在我正在使用 XHTTP 请求来访问数据,但不必如此使用它会容易得多。

function getAllBears(id){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("allBear").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "allBears", true);
    xhttp.send();
}

【问题讨论】:

    标签: javascript jquery html express


    【解决方案1】:

    您可以在 HTML 中插入一个脚本标签并将服务器端的变量字符串化,然后在窗口中读取序列化的全局变量。

    response.body = ('

    <html>
    <head>
    ...
    </head>
    <body>
        <p>text...</p>
        <script>
            window.bar = @@@
        </script>
    </body>
    </html>
    

    '.replace(@@@, JSON.stringify(bar))

    注意JSON.stringify的结果中的一些模式/字符应该被替换,一个更安全的方法如下:

    function toJSONSafely (obj: any) {
        return JSON.stringify(obj)
            .replace(/\u2028/g, '\\u2028')
            .replace(/\u2029/g, '\\u2029')
            .replace(/<\/script>/g, '<\\/script>')
    }
    

    【讨论】:

    • 这是否意味着您将 HTML 写为字符串,而不是文件?
    • 可以,不过你也可以保存为文件,通过fs.readFileSync阅读
    【解决方案2】:

    在 html 代码中使用您的 javascript,即内联 javascript 如下图

    <html>
    <head>
    </head>
    <body>
        <p>use this code </p>
        <script>
            function getAllBears(id){
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("allBear").innerHTML = this.responseText;
            }
        };
        xhttp.open("GET", "allBears", true);
        xhttp.send();
    }
        </script>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      相关资源
      最近更新 更多