jQuery Node.js - 提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8624093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:46:59  来源:igfitidea点击:

Node.js - submit form

jquerynode.jsexpresssubmit

提问by Jenan

I use node.js and express. When I press the button (btnSend), I want to send data to node.js by express (without refresh the page). How do I send data using jQuery?

我使用 node.js 和 express。当我按下按钮 (btnSend) 时,我想通过 express 将数据发送到 node.js(不刷新页面)。如何使用 jQuery 发送数据?

<form action="/Send" method="post">
Username: 
<input type="text" name="user" id="txtUser" />
<input type="submit" value="Submit" id="btnSend" />
</form>

回答by Xavi

Here's a rough outline of what your jQuery should look like:

以下是您的 jQuery 外观的粗略轮廓:

$("form").submit(function(e) {
    e.preventDefault(); // Prevents the page from refreshing
    var $this = $(this); // `this` refers to the current form element
    $.post(
        $this.attr("action"), // Gets the URL to sent the post to
        $this.serialize(), // Serializes form data in standard format
        function(data) { /** code to handle response **/ },
        "json" // The format the response should be in
    );
});

This code snippet finds all form elements on the page and listens for a submit event from them. A form can be submit in a number ways (e.x. clicking a submit button, hitting enter, etc...), so for the sake of usability, it's best to listen for submit events directly opposed to listening for click events key on submit buttons.

此代码片段查找页面上的所有表单元素并侦听来自它们的提交事件。表单可以通过多种方式提交(例如单击提交按钮,按 Enter 等...),因此为了可用性,最好直接监听提交事件,而不是监听提交按钮上的单击事件键.

When a submit event does occurs, the code above first prevents the default browser actions (which among other things refreshes the page) by calling e.preventDefault. It then uses $.postto send the form data to the url specified in the action attribute. Note that $.fn.serializeis used to serialize the form data in a standard format.

当提交事件发生时,上面的代码首先通过调用e.preventDefault. 然后它使用$.post将表单数据发送到 action 属性中指定的 url。请注意,$.fn.serialize用于以标准格式序列化表单数据。

Your express code should look something like this:

你的快递代码应该是这样的:

var express = require('express')
  , app = express.createServer();

app.use(express.bodyParser()); // Automatically parses form data

app.post('/Send', function(req, res){ // Specifies which URL to listen for
  // req.body -- contains form data
});

app.listen(3000);

The documentation on express.bodyParseris a bit sparse, but after a bit of code spelunkingit looks like it uses node-querystringunderneath the covers.

上的文档express.bodyParser有点稀疏,但经过一些代码探索后,它看起来像是在幕后使用node-querystring

Hope this helps!

希望这可以帮助!