无法使用ajax将表单数据发送到服务器端(nodejs)

时间:2016-03-30 20:14:31

标签: javascript jquery ajax node.js forms

我正在尝试通过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!");
});

我正在尝试这个但是我无法成功发送表格,并且在点击提交时,我得到了#34;嘿嘿&#34;和一个空{}作为记录输出。无论如何,我都无法在客户端记录formData

有人可以指出我可能做错了吗?

1 个答案:

答案 0 :(得分:0)

您没有将form分配给formData(),这就是您没有向服务器发送任何数据的原因。

var myForm = $('#sendCoordinates')[0];
var formData = new FormData(myForm);