如何使用循环将多个数据发送到服务器
const submit = e => {
e.preventDefault();
fetch('', {
method: 'POST',
body: JSON.stringify({
product_option_id: 1,
quantity: 2,
}),
})
.then(response => response.json())
.then(result => {
if (result.success) {
goToCart();
} else {
alert('error');
}
});
};
我有一个问题将数据发送到使用Fetch发送数据以后端。 例如,我以阵列格式的product_option_id为结果= [4,3]。 例如,我的数量格式为count = [1,2]。因此,在这里我有product_option_id:4,其数量为1,我也有product_option_id:3,其数量为2。如果我必须单独发送这些数据,一个一个接一个地发送到上述而不是发送数组,我可以写一个If语句像这样的身体?
fetch('', {
method: 'POST',
body: JSON.stringify({
for (let i =0; i < result.length; i++) {
product_option_id: result[i],
quantity: count[i],
}
}),
})
先感谢您。
const submit = e => {
e.preventDefault();
fetch('', {
method: 'POST',
body: JSON.stringify({
product_option_id: 1,
quantity: 2,
}),
})
.then(response => response.json())
.then(result => {
if (result.success) {
goToCart();
} else {
alert('error');
}
});
};
I have a question regaring sending data to backend using fetch.
I have product_option_id in array format as result = [4, 3] for example.
And I have quantity in array format as count = [1, 2] for example accordingly. So here I have product_option_id: 4 and its quantity is 1 and I also have product_option_id: 3 and its quantity is 2. If I have to send these data separately one after another one as above instead of sending array, can I write an if statement like this in body?
fetch('', {
method: 'POST',
body: JSON.stringify({
for (let i =0; i < result.length; i++) {
product_option_id: result[i],
quantity: count[i],
}
}),
})
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您的目标概述。您拥有以下数据结构:
...您想将它们作为一系列对象发送到服务器:
为此,您在正确的行上,但是您不能使用在另一行内循环。尝试用以下的呼叫来替换您的“ for”
。功能。
Firstly, an overview of your objective. You have the following data structures:
... and you want to send them to the server as an array of objects like:
To do this, you are on the right lines, but you can't use a
for
loop inside another line. Try replacing your 'for' with a call to Array.map() as follows:I refactored your code into smaller functions to make it easier to read for the benefit of anyone reading this, but you could call result.map inline inside your original function.