简体   繁体   English

如何在 POST 方法中传递多个变量?

[英]How to pass multiple variables in a POST method?

I can't figure out how to pass in multiple variables in the body of the post method.我不知道如何在 post 方法的主体中传递多个变量。 What I want to achieve is passing all the itemId's for the cart to be sent to the checkout screen of my site.我想要实现的是将购物车的所有 itemId 传递到我网站的结帐屏幕。 I'll give an example (I know the code is wrong but it shows what I want)我会举一个例子(我知道代码是错误的,但它显示了我想要的)

function purchaseClicked() {
        var cartItems = document.getElementsByClassName('cart-items')[0] // the div of where the cart rows are stored

            fetch('/create-checkout-session', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body:
                    JSON.stringify ({
                        items: // the items passed to the checkout screen with the quantity
                        [
                            for (var i = 0; i < cartItems.length; i++) { // a for loop so all the items in the cart will be passed through to the checkout screen

                                var cartRow = document.getElementsByClassName('cart-row')[i] // getting all the rows with the cart item

                                var itemId = cartRow.id // the id that belongs to the cart item
                                
                                {id: itemId , quantity:2}, // passing the id and quantity to the checkout screen
                            }
                        ]
                    })
                })
                .then(res => {
                    if (res.ok) return res.json()
                    return res.json().then(json => Promise.reject(json))
                })
                .then(({url}) => {
                    window.location = url
                })
                .catch(e => {
                    console.error(e)
                })
            
    }

expected that the id's of all the items in the cart would be sent with the prices on my server to the checkout screen (the checkout system is stripe)预计购物车中所有商品的 ID 将与我服务器上的价格一起发送到结帐屏幕(结帐系统是条纹的)

You can try something like this:你可以尝试这样的事情:

 items: cartItems.map((item, index) => {id: document.getElementsByClassName('cart-row')[index], quantity: 2 })

A better way would be to include the id and quantity in the objects inside the cartItems array and so it like this:更好的方法是将 id 和数量包含在 cartItems 数组中的对象中,如下所示:

 items: cartItems.map((item) => {id: item.id, quantity: item.quantity })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM