一、form表單提交數據
數據流向:前端 - > 後端
1、get方法 (action是提交路徑,method是提交方法,get方法可以不寫)
前端:
<form action="/getuserinfo" method="get">
id:<br>
<input type="text" name="id"><br>
名字:<br>
<input type="text" name="name">
<input type="submit" value="提交">
<br>
</form>
後端:
下面爲了方便使用的都是express框架,用http server裏面的解析稍微有些不一樣,比如需要用url模塊來解析req.url,express框架的安裝可以參考另一篇文章:https://blog.csdn.net/chen_soldier/article/details/87855187
router.get('/getuserinfo', function(req, res, next) {
var query = req.query;
var id = query.id;
var name = query.name;
console.log(id);
console.log(name);
res.end();
});
注:末尾要加上res.end()或其他返回的html等,不然網頁會一直等待
2、post方法
前端:
<form action="/login" method="POST">
name:<br>
<input type="text" name="name"><br>
password:<br>
<input type="text" name="password">
<input type="submit" value="提交">
<br>
</form>
後端:
router.post('/login', function(req, res, next) {
var body = req.body;
var name = body.name;
var password = body.password;
console.log(name);
console.log(password);
res.end();
});
注:用http server需要用querystring模塊來解析req.rawBody
form表單提交後會進行頁面跳轉,如果不希望跳轉,可以在頁面中定義一個不可見的iframe:
<iframe id="iframe_display" name="iframe_display" style="display: none;"></iframe>
然後將form的target指向該iframe:
<form action="/login" method="POST" target="iframe_display">