【问题标题】:not render html to client with websockets不使用 websockets 将 html 呈现给客户端
【发布时间】:2013-07-19 01:39:56
【问题描述】:

我使用 nodejs v0.10.12 并使用 websockets。在服务器端,我有一个类似

的代码
//the http server
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end(clientHtml);
});
server.listen(8000, function() {
    console.log((new Date()) + ' Server is listening on port 8000');
})

//the websockets server
var wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

//connections, getting data from client , etc, etc

//try to send data to client
 connection.send('<b>Name</b></br>'+
result.row[i].p_name+
'</br></br><b>Description</b></br><textarea rows="20" cols="60">'
+result.rows[i].p_descr+
'</textarea>');

我想通过 websockets 将 connection.send 中包含的数据从服务器发送到客户端。 问题是,在客户端,html标签也会呈现,在浏览器上我得到

<b>Name</b></br>testpoint5</br></br><b>Description</b></br><textarearows="20"cols="60">testpoint5</textarea>

我搜索了“通过 websockets 的 html 标签”等,但没有任何用处...

有什么建议吗?如何让 html 标签在客户端“工作”,而不仅仅是渲染?

谢谢

【问题讨论】:

    标签: node.js websocket


    【解决方案1】:

    您稍后会尝试将该数据插入 DOM 吗?

    在这种情况下,您需要转义您的标签。我的意思是&amp;lt;应该变成&amp;lt;&amp;gt;应该变成&amp;gt;

    您还需要转义其他字符。在谷歌上查找“转义 html 实体”。

    您应该在服务器端执行此操作:

    connection.send("&lt;b&gt;Name&lt;/b&gt;&lt;/br&gt;"+result.rows[i].p_name+"&lt;/br&gt;&lt;/br&gt;&lt;b&gt;Description&lt;/b&gt;&lt;/br&gt;&lt;textarearows="20"cols="60"&gt;"+result.rows[i].p_descr+"&lt;/textarea&gt;")
    

    【讨论】:

    • 稍后,我将数据呈现在客户端的div 中。感谢您的提示,但不幸的是,它没有用。 &amp;lt;&amp;gt; 仍会在浏览器上呈现
    • 你应该包含渲染代码,因为这是这里的问题
    • 抱歉这个愚蠢的问题,但是“渲染代码”是指前端代码还是后端代码?还是我在浏览器上得到的代码?
    • 将 websocket 中的内容插入页面的前端代码(并且无法正常工作)
    • 我只是修复它。在前端,在onmessage 函数中,我有response.textContent = received_msg; 来呈现数据,“响应”是一个简单的div。我应该有document.getElementById("response").innerHTML=received_msg;。现在工作得很好,无需转义 html 实体。这如此很尴尬,由于我自己的疏忽造成了“问题”。无论如何,mkoryak,谢谢你的时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多