溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用nodejs怎么獲取表單數(shù)據(jù)

發(fā)布時間:2021-06-02 15:59:04 來源:億速云 閱讀:325 作者:Leah 欄目:開發(fā)技術(shù)

使用nodejs怎么獲取表單數(shù)據(jù)?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

1、首先npm初始化,下載express包,導(dǎo)入模塊后創(chuàng)建服務(wù)對象

//導(dǎo)入express模塊
const express = require("express");
// 創(chuàng)建服務(wù)器對象
const app = express();

form表單傳遞

這種通過from表單的特性,可以點(diǎn)擊表單中button的type為submit的按鈕,會提交表單數(shù)據(jù)。形式是以一種對象方式,屬性名為input標(biāo)簽中name值,屬性值為input標(biāo)簽value值,下面例子來看看具體寫法。

<form action="/todata" method="POST">
        <table>
            <tr>
                <td>姓名</td>
                <td> <input type="text" name="user" id=""></td>
            </tr>
            <tr>
                <td>密碼</td>
                <td> <input type="text" name="password" id=""></td>
            </tr>
            <tr>
                <button type="submit">提交</button>
            </tr>
        </table>
</form>

由于表單提交是post請求,在后端nodejs代碼中需要對post請求數(shù)據(jù)接收需要做解析響應(yīng)頭的處理app.use(bodyParser.urlencoded({ extended: false })),然后用req.body來表示前端傳遞過來的數(shù)據(jù)。具體后端代碼如下。

const express = require("express");
const app = express();
app.use(express.static("./"))
var bodyParser = require('body-parser')
//  解析 application/x-www-form-urlencoded響應(yīng)頭
app.use(bodyParser.urlencoded({ extended: false }))
app.post("/todata",(req,res)=>{
    console.log(req.body);
    res.send("提交成功")
})
app.listen("80",()=>{
    console.log("成功");
})

通過終端運(yùn)行node代碼,來看看結(jié)果

使用nodejs怎么獲取表單數(shù)據(jù)

ajax請求傳遞

在向后端發(fā)送請求時,常用到get、post請求,同樣,表單的數(shù)據(jù)可以通過ajax以post請求發(fā)送數(shù)據(jù)給后端。以上面例子為基礎(chǔ),該方法的前端代碼如下。

	 $("#inp3").on("click",function(){
        let user = $("#inp1").val();
        let password = $("#inp2").val();
        $.ajax({
        url:"todata",
        type:"post",
        data:{
            user,
            password
        },
        success:(data)=>{
            alert(data)
        }
         })
    })

這里,我們將兩個input的值獲取到,然后綁定提交按鈕的提交按鈕進(jìn)行ajax請求發(fā)送,發(fā)送給后端的數(shù)據(jù)存儲在data屬性中。后端同樣通過req.body獲取到。這里需要特別注意的是form表單不需要寫action值,表單中button按鈕需要阻止默認(rèn)行為(不然會點(diǎn)擊直接發(fā)送請求導(dǎo)致ajax請求會失敗),或是用input標(biāo)簽type為button類型。

使用nodejs怎么獲取表單數(shù)據(jù)

表單序列化

這種發(fā)送是表單提交的常用方法,它也是通過ajax發(fā)送請求,也可以將name屬性作為發(fā)送后端的屬性名直接發(fā)送。可以說是以上兩種方法的結(jié)合。

		$("#inp3").on("click",function(){
        $.ajax({
        url:"todata",
        type:"post",
        data:$("form").serialize(),
        success:(data)=>{
            alert(data)
        }
         })
    })

只需要通過$(“form”).serialize()這個方法,就能獲取含name屬性值。

使用nodejs怎么獲取表單數(shù)據(jù)

關(guān)于使用nodejs怎么獲取表單數(shù)據(jù)問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI