簡體   English   中英

如何將 JS 表單中的列表作為 JSON 傳遞到后端?

[英]How can I pass a list from a form in JS as JSON to the backend?

這是我要發送到后端以創建Car對象的列表(此 class 也在下面顯示)。

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

public class Car {
private String name;

public String getName() {
    return name;
}

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

}

I need to send my list from the form as JSON and assign the items of my list to the cars property inside that JSON because my sent JSON from JS will be deserialized to this class:

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
                    ]
               })
            })
        });

我還會提到,我只想從我的列表中獲取所有項目,無論它們的數量如何。 換句話說,無論我要發送到后端的汽車數量(目前有兩輛汽車),我都希望我的代碼能夠正常工作。

我建議您再次閱讀參考資料:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

查看method (HTTP 方法)和action (后端 URL)HTML 屬性

我解決了我的問題。 現在它按預期工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM