簡體   English   中英

無法使用Ajax將表單數據發送到服務器端(nodejs)

[英]Unable to send form data to server side (nodejs) using ajax

我正在嘗試通過Ajax將表單數據發送到Node.js服務器。 以前在這個帖子上問過。

這是我的代碼:

<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!");
});

我正在嘗試執行此操作,但是無法成功發送表單,並且在單擊Submit時,我得到“嘿”和一個空{}作為記錄的輸出。 formData ,我無法在客戶端上記錄formData

有人可以指出我可能做錯了什么嗎?

您沒有為formData()分配form ,這就是為什么不向服務器發送任何數據的原因。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM