【发布时间】:2016-03-30 20:14:30
【问题描述】:
我正在尝试通过 ajax 将表单数据发送到 nodejs 服务器。以前在这个post上问过。
我的代码如下所示:
<div id="inputid" style="width: 400px; height:400px">
<p> Please enter a value between -90 and 90 for lat, and -180 and 180 before hitting
submit.</p>
<form id="sendCoordinates" action="http://localhost:8080/geodata" method="post">
MinLat: <input type="text" name="MinLat" value="15" id="minlat"><br>
MaxLat: <input type="text" name="MaxLat" value="25" id="maxlat"><br>
MinLong: <input type="text" name="MinLong" value="-10" id="minlong"><br>
MinLong: <input type="text" name="MaxLong" value="120" id="maxlong"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$(document).ready(function() {
console.log("hi hi");
$("#sendCoordinates")
.on('submit', function(e) {
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray();
$.each(params, function(i, val) {
// console.log(val);
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
console.log("hi helo");
}
});
});
});
</script>
</div>
我的服务器端代码如下所示:
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
// for debugging purposes, just logging the request to check
// if request received
app.post("/geodata", function(req, res) {
console.log("hey");
console.log(req.body);
res.send("hi back!");
});
我正在尝试这个,但我无法成功发送表单,并且在点击提交时,我得到“嘿”和一个空的 {} 作为日志输出。无论如何,我无法在客户端记录formData。
有人可以指出我可能做错了什么吗?
【问题讨论】:
-
对于初学者来说,
$(sendCoordinates)应该是$("#sendCoordinates")。 -
@Pointy 感谢您指出这一点。不幸的是,它不能解决问题。 :(
-
您认为“成功”事件从何而来?如果你想处理“提交”事件,你应该把它传递给
.on()。 -
@Pointy 嗯,我已将其更改为“提交”。它仍然没有发送表单数据:/
-
您拨打了
e.preventDefault()电话,这就是您收到两个表单帖子的原因。
标签: javascript jquery ajax node.js forms