简体   繁体   English

在 JQuery 中创建 JSON 对象的 JSON 数组

[英]Creating a JSON Array of JSON Objects in JQuery

I'm trying to send a JSON Object to my back-end.我正在尝试将 JSON 对象发送到我的后端。 Basically what I'm trying to do is get the input of 2 textfields and then a list of all selected text boxes.基本上我想要做的是获取 2 个文本字段的输入,然后是所有选定文本框的列表。 My javascript code so goes like this:我的 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
            }
        });

I'm really not an expert yet with javascript, but from what I've found from other anwers and posts this is what I could put together and thought it could actually work.我真的不是 javascript 专家,但从我从其他回答和帖子中发现的内容来看,这是我可以组合在一起并认为它实际上可以工作的内容。 The back-end part is working fine, as I tested it with PostMan and perfectly works fine.后端部分工作正常,因为我用 PostMan 对其进行了测试,并且工作正常。 This is what the JSON, I;m sending from PostMan, looks like:这是我从 PostMan 发送的 JSON 的样子:

{
    "name": "Wanda",
    "surname": "Maximoff",
    "abilities": [
            {
                "id": 4,
                "ability": "Telechinesis"
            },
            {
                "id": 3,
                "ability": "Flight" 
            }
        ]
}

What could be wrong in the JavaScript code? JavaScript 代码中可能有什么问题?

Here is a sample of one of the textfields and one of the checkboxes:以下是文本字段之一和复选框之一的示例:

<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>

Apparently the javascript code is not parsing correctly the value and ids of the checkboxes.显然,javascript 代码没有正确解析复选框的值和 ID。 How can I make of the checkboxes HTML content, a JSON array correctly formatted如何制作复选框 HTML 内容,格式正确的 JSON 数组

The main issue seems to be extracting the abilities from the HTML.主要问题似乎是从 HTML 中提取能力。
To do that, iterate over all checked checkboxes, then use jQuery functions like .closest() or .find() to grab the <label> .为此,请遍历所有选中的复选框,然后使用.closest().find()等 jQuery 函数来获取<label> From there you can extract the required information.您可以从那里提取所需的信息。

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM