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
]
})
})
});
我还要提到的是,我只想从我的列表中获取所有项目,而不管它们的数量。换句话说,我希望我的代码能够正常工作,无论我想将多少辆车(目前有两辆车)发送到后端
# 1 楼答案
我建议您再次阅读参考资料:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
请参阅
method
(HTTP方法)和action
(后端URL)HTML属性# 2 楼答案
我解决了我的问题。现在它如预期的那样工作: