Sometimes, we want to append array to FormData and send via Ajax with JavaScript.
In this article, we’ll look at how to append array to FormData and send via Ajax with JavaScript.
How to append array to FormData and send via Ajax with JavaScript?
To append array to FormData and send via Ajax with JavaScript, we can use the spread operator.
For instance, we write
const formData = new FormData();
const arr = ["this", "is", "an", "array"];
for (const a of arr) {
formData.append("arr[]", a);
}
console.log(...formData);
to loop through the arr array and call formData.append with the key and value of each FormData entry.
Then we use the spread operator to spread the formData key-value entries as arguments of console.log as arrays.
Conclusion
To append array to FormData and send via Ajax with JavaScript, we can use the spread operator.