我正在嘗試使用nodejs製作迭代表單。NodeJS:如何有多個方法發佈
這裏是我的網頁
<!DOCTYPE html>
<html>
<script>
$('#ping-button').click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/process_test'
});
});
</script>
<body>
<form action="http://127.0.0.1:3000/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
<br>
<form action="http://127.0.0.1:3000/process_post" method="POST">
Team: <input type="text" name="team"> <br>
Player: <input type="text" name="player">
<input type="submit" value="Submit">
<br><br>
<button id='ping-button'>Ping</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</form>
</body>
</html>
,這裏是我的app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('test'));
app.get('/index.html', function (req, res) {
res.sendFile(__dirname + "/" + "index.html");
})
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
app.post('/process_test', urlencodedParser, function (req, res) {
console.log("Ping");
res.end(JSON.stringify("Ping"));
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
team:req.body.team,
player:req.body.player
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(3000, function() {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
,所以我有兩種形式和一個按鈕。第一種形式與process_get
方法相關,第二種形式與process_post
方法相關,並且該按鈕與process_test
方法相關聯。
這兩種形式都給出了預期的結果。當我點擊該按鈕時,它會轉到process_post
方法而不是process_test
爲什麼會發生這種情況?
完美!非常感謝:)現在它變得更有意義 – AbtPst