本文介绍了表单提交后将数据从NodeJS发送回同一html页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In an HTML page called "history.html", I have a form with the POST method that I submit to NodeJS server to make some operations.

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

some form stuff

</form>

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

This is the code on the server that receives the form and makes some operations:

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 对象(它们不像数组那样用方括号括起来),在这个例子中,我只放了其中的两个:

The resulting output of this particular Find operation is an set of many JSON objects (they are not surrounded with square brackets like in an Array), in this example, I just put 2 of them:

    {
        "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.

What I need to achieve, is to somehow send back the variable datos that contains the above result, back to the same HTML where I submitted the form.

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

If I use the res.send(datos), what I get is the data itself represented on the browser. I need to get back to the HTML page but having the variable available to use it and perform other operations directly on the page.

我一直在网上搜索,但没有找到如何做到这一点.
非常感谢所有能帮助我解决这个问题的人.

I have been searching the web with no luck on how to do this.
Thank you very much to everyone that can help me with this.

推荐答案

您无法将数据发送到 HTML 页面. HTML 是一种静态文件格式,无法单独接收数据.服务器可以,但不是 HTML 文件.

You can't send data to an HTML page. HTML is a static file format and cannot receive data by itself. A server can, but not an HTML file.

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

What you can do however, is intercept your post request on the client side, send it to the client using XHR and receiving back the data on the client side again, then do whatever you want when the script receives datos. Basically everything happens between the JavaScript part of the page and the Node server that receives POST data and sends back datos.

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

Here's a simple example of how you can intercept the POST request on the client side:

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:上面的代码段将因网络错误而失败,因为只有客户端脚本存在 - https://your-domain.com/path/to/api,但您已经在问题中包含了正确的服务器代码.只需通过 res.send(datos) 结束服务器脚本.

PS: The above snippet will fail with a network error because only the client-side script is present - there is nothing running at https://your-domain.com/path/to/api, but you already included the right server code in your question. Just end the server script by res.send(datos).

这篇关于表单提交后将数据从NodeJS发送回同一html页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 23:42