Node.js - 提交表单

Jen*_*nan 8 jquery submit node.js express

我使用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>
Run Code Online (Sandbox Code Playgroud)

Xav*_*avi 17

以下是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
    );
});
Run Code Online (Sandbox Code Playgroud)

此代码段查找页面上的所有表单元素,并从中侦听提交事件.表单可以通过多种方式提交(单击提交按钮,点击输入等等),因此为了便于使用,最好是直接反对提交事件,而不是在提交按钮上监听点击事件键.

当发生提交事件时,上面的代码首先通过调用来阻止默认的浏览器操作(其中包括刷新页面)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);
Run Code Online (Sandbox Code Playgroud)

文档express.bodyParser有点稀疏,但在一些代码探测后,它看起来像是在封面下使用了node-querystring.

希望这可以帮助!