繁体   English   中英

如何将内容传递给客户端 html 页面中的元素?

[英]How can I pass content to an element in clients html page?

我目前正在使用 Node.js 来提供一个网页,该网页接收存储在 mongodb 服务器上的用户输入。 该网页还显示输入的指定或所有用户输入。 我想弄清楚如何将用户输入从 node.js 传递到<p>元素。

在我的 node.js 文件中,我将用户数据作为字符串进行响应,如下所示:

response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stringifyMongoDBCollection(user_data_collection));
response.end();

当我这样做时,这会重定向客户端将内容显示为我期望的text/plain 下一步是只更新<p>的内容。 我怎样才能做到这一点? 我想过使用新填充的<p>重新提供整个 html 内容,但这会使所有当前用户输入消失......

用户数据将是一个 mongodb 集合数组,如下所示:

 [ { _id: 5dda17065f7e9b64282e7291,
    date: 'Sat Nov 23 2019 21:37:10 GMT-0800 (Pacific Standard Time)',
    field: '127' },
  { _id: 5dda18ecf330d521a035c444,
    date: 'Sat Nov 23 2019 21:45:16 GMT-0800 (Pacific Standard Time)',
    field: 125},
  { _id: 5dda1951f330d521a035c445,
    date: 'Sat Nov 23 2019 21:46:57 GMT-0800 (Pacific Standard Time)',
    field: '111' } ]

你可以做这样的事情。

在节点部分

res.status(200).send(stringifyMongoDBCollection(user_data_collection));

客户端

 function getContent() { $.ajax({ url: "https://jsonplaceholder.typicode.com/todos", success: function (res) { if (res) { res = res.slice(0, 5); // limiting data to 5 var val = ''; res.forEach(todo => { val += '<p><b>Title:</b>' + todo.title + ' <b>Completed:</b> ' + todo.completed + '</p>'; }); } $("#content").html(val); }, error: function () { var val = '<p>Error in loading content</p>' $("#content").html(val); } }); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="getContent()">Get Content</button> <h1>Todo</h1> <div id="content"></div>

参考

jQuery ajax() 方法

Node.js - 响应对象

AJAX 介绍

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM