【问题标题】:Creating a JSON Array of JSON Objects in JQuery在 JQuery 中创建 JSON 对象的 JSON 数组
【发布时间】: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 问题:请参阅 thisthis。还值得注意的是,您可以使用 map() 改进 JS:jsfiddle.net/RoryMcCrossan/vgxwrnmq
  • 好的,在这种情况下打开开发工具并检查您发送的请求的正文,以确保它是有效的 JSON 并且格式与您在 Postman 中使用的格式相同
  • @Sarfraaz 如果不进行字符串化,jQuery 会将对象转换为查询字符串。无论如何,这是实时代码,请求似乎很好:jsfiddle.net/khrismuc/4fL7tujv
  • 可以添加 HTML 吗?因为复选框通常没有值或文本内容。
  • 这是一个数组;它总是有索引。

标签: javascript java jquery json ajax


【解决方案1】:

主要问题似乎是从 HTML 中提取功能。
为此,遍历所有选中的复选框,然后使用 jQuery 函数,如 .closest().find() 来获取 &lt;label&gt;。从那里您可以提取所需的信息。

function insertNewHero() {
  var abilities = {};
  $('#newhero .custom-checkbox input:checked').each(function() {
    const $label = $(this).closest("div").find("label");
    abilities[$label.data("id")] = $label.text();
  });

  var superhero = {
    name: "Wanda",
    surname: "Maximoff",
    abilities
  }
  
  console.log(superhero);

  // send data to backend
}

$('#newhero').on("submit", function(e) {
	e.preventDefault();
  insertNewHero();
});
#newhero, .form-group {
  padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<form id="newhero">
  <div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input" style="" id="InsertFlight">
    <label class="custom-control-label" for="InsertFlight" data-id="3">Flight</label>
  </div>
  <div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input" style="" id="InsertTelekinesis">
    <label class="custom-control-label" for="InsertTelekinesis" data-id="4">Telekinesis</label>
  </div>
  <div class="form-group">
    <input type="submit">
  </div>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-03
    • 2013-08-28
    • 2013-07-22
    • 2021-09-22
    • 1970-01-01
    • 2018-11-08
    • 2017-09-27
    相关资源
    最近更新 更多