[英]Unable to send form data to server side (nodejs) using ajax
I am trying to send form data via ajax to a nodejs server. 我正在尝试通过Ajax将表单数据发送到Node.js服务器。 Previously asked on this post .
以前在这个帖子上问过。
Here's what my code looks like: 这是我的代码:
<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>
My server side code looks like this : 我的服务器端代码如下所示:
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!");
});
I am trying this out but I am unable to send the form successfully, and upon hitting submit, I get "hey" and an empty {} as logged output. 我正在尝试执行此操作,但是无法成功发送表单,并且在单击Submit时,我得到“嘿”和一个空{}作为记录的输出。 I am not able to log the
formData
on the client side, regardless. formData
,我无法在客户端上记录formData
。
Can someone point out what I might be doing wrong? 有人可以指出我可能做错了什么吗?
You didn't assign a form
to formData()
that's why you're not sending any data to the server. 您没有为
formData()
分配form
,这就是为什么不向服务器发送任何数据的原因。
var myForm = $('#sendCoordinates')[0];
var formData = new FormData(myForm);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.