Node.js-提交表单 [英] Node.js - submit form
问题描述
我使用node.js进行表达.当我按下按钮(btnSend)时,我想通过express将数据发送到node.js(不刷新页面).如何使用jQuery发送数据?
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?
<form action="/Send" method="post">
Username:
<input type="text" name="user" id="txtUser" />
<input type="submit" value="Submit" id="btnSend" />
</form>
推荐答案
以下是jQuery的大致轮廓:
Here's a rough outline of what your jQuery should look like:
$("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
);
});
此代码段查找页面上的所有表单元素,并从中监听提交事件.表单可以通过多种方式提交(例如,单击提交按钮,按Enter等),因此,出于可用性的考虑,最好侦听提交事件,而不是直接侦听提交按钮上的单击事件键
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.
发生提交事件时,上面的代码首先通过调用 $ .post 将表单数据发送到action属性中指定的url.请注意, $.fn.serialize
用于以标准格式序列化表单数据.
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 $.post to send the form data to the url specified in the action attribute. Note that $.fn.serialize
is used to serialize the form data in a standard format.
您的快递代码应如下所示:
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);
express.bodyParser
上的文档有点稀疏,但是在代码拼写,看起来它在封面的下面使用了 node-querystring .
The documentation on express.bodyParser
is a bit sparse, but after a bit of code spelunking it looks like it uses node-querystring underneath the covers.
希望这会有所帮助!
这篇关于Node.js-提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!