为了账号安全,请及时绑定邮箱和手机立即绑定

服务器端将信息发送到普通 HTML

服务器端将信息发送到普通 HTML

ITMISS 2023-10-24 17:20:12
是否可以像使用 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();}
查看完整描述

2 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

您可以在 HTML 中插入脚本标记,并对服务器端的变量进行字符串化,然后在窗口上读取序列化的全局变量。


响应.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>')

}


查看完整回答
反对 回复 2023-10-24
?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

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


查看完整回答
反对 回复 2023-10-24
  • 2 回答
  • 0 关注
  • 61 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信