有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript如何将JS表单中的列表作为JSON传递到后端?

这是我要发送到后端以创建Car对象的列表(下面还显示了这个类)

<form id="newBrand">
        <fieldset>
            <ul id="formCars">
              <li>
                <legend>Car 1</legend>
                <label>Name
                    <input type="text" name="carName1" />
                </label>
              </li>
              <li>
                <legend>Car 2</legend>
                <label>Name
                    <input type="text" name="carName2" />
                </label>
              </li>
            </ul>
        </fieldset>
    <button type="submit">ADD</button>
</form>

这是Car类:

public class Car {
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

我需要将表单中的列表作为JSON发送,并将列表中的项目分配给该JSON中的cars属性,因为我从JS发送的JSON将反序列化到此类:

public class Foo {
private Set<Car> cars;

public Set<Car> getCars() {
    return cars;
}

public void setCars(Set<Car> cars) {
    this.cars = cars;
}
}
// JS code: 
const form = document.getElementById('newBrand');

form.addEventListener('submit', async (e) => {
            e.preventDefault();

            fetch(`/brands`, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    cars: [
                          // here I need to insert my list items from the form
                    ]
               })
            })
        });

我还要提到的是,我只想从我的列表中获取所有项目,而不管它们的数量。换句话说,我希望我的代码能够正常工作,无论我想将多少辆车(目前有两辆车)发送到后端


共 (2) 个答案

  1. # 2 楼答案

    我解决了我的问题。现在它如预期的那样工作:

    body: JSON.stringify({
         cars: getFormCars()
    })
    function getFormCars() {
                let result = [];
                const cars = formCars.querySelectorAll('li');
                cars.forEach(car => {
                    var input = car.querySelector('input');
                    result.push({
                        name: input.value
                    })
                })
                return result;
            }