【发布时间】:2020-05-10 15:25:33
【问题描述】:
我正在尝试将 JSON 对象发送到我的后端。基本上我想要做的是获取 2 个文本字段的输入,然后是所有选定文本框的列表。我的 javascript 代码是这样的:
function insertNewHero() {
var selectedAbilities = [];
$('#newhero input:checked').each(function() {
selectedAbilities.push({
"id": $(this).value,
"ability": $(this).textContent
});
});
var superhero = {
"name": document.getElementById("name").value,
"surname": document.getElementById("lastName").value,
"abilities": selectedAbilities
}
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/insertNewHero",
data: JSON.stringify(superhero),
success: function (result) {
// other stuff
}
});
我还不是 javascript 方面的专家,但根据我从其他答案和帖子中发现的内容,这是我可以组合并认为它可以实际工作的内容。后端部分运行良好,因为我使用 PostMan 对其进行了测试,并且运行良好。这就是我从 PostMan 发送的 JSON 的样子:
{
"name": "Wanda",
"surname": "Maximoff",
"abilities": [
{
"id": 4,
"ability": "Telechinesis"
},
{
"id": 3,
"ability": "Flight"
}
]
}
JavaScript 代码可能有什么问题?
这是其中一个文本字段和一个复选框的示例:
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="textfield" class="form-control" id="lastName" placeholder="Last Name" required>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" style="background: #bf0000; color: #bf0000; border: solid #bf0000" id="InsertFlight">
<label class="custom-control-label" for="InsertFlight" value="3">Flight</label>
</div>
显然,javascript 代码没有正确解析复选框的值和 id。如何使复选框 HTML 内容、格式正确的 JSON 数组
【问题讨论】:
-
谷歌那个错误。这似乎不是 JS 问题:请参阅 this 和 this。还值得注意的是,您可以使用
map()改进 JS:jsfiddle.net/RoryMcCrossan/vgxwrnmq -
好的,在这种情况下打开开发工具并检查您发送的请求的正文,以确保它是有效的 JSON 并且格式与您在 Postman 中使用的格式相同
-
@Sarfraaz 如果不进行字符串化,jQuery 会将对象转换为查询字符串。无论如何,这是实时代码,请求似乎很好:jsfiddle.net/khrismuc/4fL7tujv
-
可以添加 HTML 吗?因为复选框通常没有值或文本内容。
-
这是一个数组;它总是有索引。
标签: javascript java jquery json ajax