表单到 JSON 的转换不起作用



我正在尝试将HTML中填写的表单转换为JSON请求,然后可以通过HTTP POST将其发送到服务器。虽然表单已填写,但我在 JSON 请求中看到的只是一个空的 JSON 数组。

下面给出了JS片段

$("#submitSurveyBtn").on("click", function (event) {
event.preventDefault();
var formData = JSON.stringify($("#surveyForm").serializeArray());
console.log(formData);
$.ajax({
type: "POST",
url: "/api/friends",
data: formData,
dataType: "json"
}).then(function (res) {
console.log(res)
});
});

下面给出了 HTML 代码段

<form id="surveyForm">
<div class="form-group">
<label for="nameInput">Name(Required)</label>
<input id="name" type="text" class="form-control" id="nameInput" placeholder="name">
</div>
<div class="form-group">
<label for="imgInput">Link to Photo Image (Required)</label>
<input id="imgURL" type="text" class="form-control" id="imgInput" placeholder="http://...">
</div>

代码笔 - https://codepen.io/rajdhandus/pen/pKWLzR

您的表单 HTML:

<input id="name" type="text" class="form-control" id="nameInput" placeholder="name">
....
<input id="imgURL" type="text" class="form-control" id="imgInput" placeholder="http://...">

您没有输入的名称,因此无法序列化,因为它无效

更改为:

<input id="name" name="name" type="text" class="form-control" id="nameInput" placeholder="name">
...
<input id="imgURL" name="imgURL" type="text" class="form-control" id="imgInput" placeholder="http://...">

这是你遇到的主要问题!

我更喜欢使用以下结构,但这取决于您:

$("#surveyForm").on("submit", function (e) {
e.preventDefault();
var formData = $(this).serialize();  
// ...
});

最新更新