Node.js – 提交表单
我使用node.js和express。 当我按下button(btnSend)时,我想通过快速发送数据到node.js(不刷新页面)。 我如何发送数据? 使用jQuery的?
请帮忙。
感谢您的build议。
<form action="/Send" method="post"> Username: <input type="text" name="user" id="txtUser" /> <input type="submit" value="Submit" id="btnSend" /> </form>
下面是你的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 ); });
该代码片段查找页面上的所有表单元素,并从中监听提交事件。 表单可以通过多种方式提交(例如,点击提交button,敲入回车等),所以为了可用性,最好是直接监听提交事件,而不是在提交button上监听点击事件按键。
当提交事件发生时,上面的代码首先通过调用e.preventDefault
防止默认的浏览器操作(除了刷新页面之外)。 然后使用$ .post将表单数据发送到action属性中指定的url。 请注意, $.fn.serialize
用于以标准格式序列化表单数据。
你的明码是这样的:
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 。
希望这可以帮助!