首页 > 解决方案 > 从onject生成元素后,如何根据单击的相对元素获取对象

问题描述

我正在创建一个从数据库中检索到的产品表。目前,我能够接收数据并将其显示为输入表。我想要做的是创建一个方法,在单击输入时获取产品并将其存储在变量中。

下面是生成输入表的代码:

        <table style="margin:0 auto;">
            <% products.forEach(function(product) { %>
            <tr>
                <form action="/product" method="POST">
                    <td><input class="pid" type="submit" name="pid" value="<%= product.product_id%>"
                            style="width: 100px;"></input>
                    <td><input class="product-option" type="submit" name="product"
                            value="<%= product.name%>" style="width: 500px;"></input>
                </form>
            </tr>
            <% }); %>
        </table>

whereproducts被传递给页面的对象如下所示:

例子:

  RowDataPacket {
    name: 'Vinegar - Tarragon',
    product_id: 960,
    img_src: 'https://www.sandu.in/image/cache/catalog/product/no-product-800x800.png',
    description: 'Seamless contextually-based utilisation',
    cost: 168.1,
    date_created: 2021-05-31T12:00:00.000Z,
    date_modified: null,
    date_deleted: null,
    category_id: 960,
    inventory_id: 960,
    discount_id: 960
  }

目前,当表单发布时,我有一个方法,它按名称获取元素,product,如下所示:

router.post('/product', function (req, res) {
    if (session.user) { //Session isn't relevant
        var body = ''
        req.on('data', function (data) {
            body += data;
            if (body.length > 1e6)
                req.connection.destroy();
        });

        req.on('end', function () {
            var result = qs.parse(body);
            console.log(result) //Returns "[Object: null prototype] { product: 'Vinegar - Tarragon' }"
            console.log(result.product); //Returns "Vinegar - Tarragon"
        });
    } else {
        res.redirect('/', {
            title: "Login"
        });
    }
});

有没有一种方法可以在单击输入时获取整个对象(如示例中所示),而不是仅获取产品名称?

标签: javascripthtmlnode.jsexpress

解决方案


推荐阅读