【问题标题】:Send data from NodeJS back to same html page after form submission表单提交后将数据从 NodeJS 发送回相同的 html 页面
【发布时间】:2019-06-05 11:17:50
【问题描述】:

在一个名为“history.html”的 HTML 页面中,我有一个带有 POST 方法的表单,我将它提交给 NodeJS 服务器以进行一些操作。

<form action="/history/find" method="POST">

some form stuff

</form>

这是服务器上接收表单并进行一些操作的代码:

router.post("/history/find", function (req, res) {

    var fechaInicial = req.body.fechaInicial;
    var fechaFinal = req.body.fechaFinal;
    var contaminante = req.body.contaminante;

    Comment.find(
        {
            "data.time.s": {
                "$gte": fechaInicial,
                "$lte": fechaFinal
            }
        },
        {
            [contaminante]: 1,
            "data.time.s": 1,
            "_id": 0
        }, function (error, datos) {

            res.send(datos);

        });

});

这个特定 Find 操作的结果输出是一组许多 JSON 对象(它们不像在数组中那样用方括号括起来),在这个例子中,我只放了其中的 2 个:

    {
        "data": {
            "iaqi": {
                "co": {
                    "v": 3.2
                }
            },
            "time": {
                "s": "2019-05-14 12:00:00"
            }
        }
    },
    {
        "data": {
            "iaqi": {
                "co": {
                    "v": 4.8
                }
            },
            "time": {
                "s": "2019-05-15 00:00:00"
            }
        }
    }

我需要实现的是,以某种方式将包含上述结果的变量 datos 发送回我提交表单的同一 HTML。

如果我使用 res.send(datos),我得到的是浏览器上表示的数据本身。我需要返回 HTML 页面,但有可用的变量来使用它并直接在页面上执行其他操作。

我一直在网上搜索,但不知道如何做到这一点。
非常感谢所有可以帮助我的人。

【问题讨论】:

  • 为什么不能再使用res.send(JSON.stringify(datos))和HTML页面JSON.parse呢?
  • 如果我使用res.send(JSON.stringify(datos)),我只会得到相同的输出,但在 HTML 页面上用方括号(作为数组)包围,我不知道如何返回同一页面,但只是带有一个新变量,其中包含数据。

标签: javascript node.js mongodb response


【解决方案1】:

您不能将数据发送到 HTML 页面。 HTML 是一种静态文件格式,不能自行接收数据。服务器可以,但不能是 HTML 文件。

但是,您可以做的是在客户端拦截您的发布请求,使用XHR 将其发送到客户端并再次在客户端接收数据,然后在脚本收到@987654323 时执行您想要的任何操作@。基本上一切都发生在页面的 JavaScript 部分和接收 POST 数据并发回 datos 的 Node 服务器之间。

下面是一个简单的例子,说明如何在客户端拦截 POST 请求:

document.querySelector('form').onsubmit = evt => {

  // don't submit the form via the default HTTP redirect
  evt.preventDefault();
  
  // get the form values
  const formData = {
    name1: document.querySelector('input[name=name1]').value,
    name2: document.querySelector('input[name=name2]').value
  }
  console.log('formData:', formData);
  
  // send the form encoded in JSON to your server
  fetch('https://your-domain.com/path/to/api', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(formData),
  })
  
  // receive datos from the server
  .then(resp => resp.json())
  .then(datos => {/* do what you want here */})
  
  // catch potential errors
  .catch(err => console.log('an error happened: '+err));
  
}
<form>
  <input name="name1" value="value1">
  <input name="name2" value="value2">
  <button type="submit">Submit</button>
</form>

PS:上面的 sn-p 将因网络错误而失败,因为只有客户端脚本存在 - https://your-domain.com/path/to/api 没有运行任何东西,但您已经在问题中包含了正确的服务器代码。只需通过res.send(datos) 结束服务器脚本即可。

【讨论】:

  • 非常感谢尼诺!现在我知道为什么当我问错了问题时,我无法找到问题的答案。按照您所说的方式,我可以在客户端捕获包含查询中所有数据的数组。
  • 没错,你的问题就是the XY problem的完美例子;)
猜你喜欢
  • 1970-01-01
  • 2021-01-01
  • 2019-02-10
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 2013-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多