【问题标题】:Converting button values to JSON将按钮值转换为 JSON
【发布时间】:2017-03-27 16:28:39
【问题描述】:

我正在使用 node.js 和 mongodb 构建一个 Web 应用程序。

所以我的应用程序有一个表,它从数据库中将不同的信息循环到表中。

我在this tutorial 之后构建了一个删除功能,但我遇到了问题。

这是我的 onclick 函数的 js 代码。

function myFunction() {

    fetch('guests', {
        method: 'delete',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'guestnumber': '3'
        })
    })
        .then(res => {
            if (res.ok) return res.json();
        }).
        then(data => {
            console.log(data);
            window.location.reload();
        });
}

现在这段代码工作得很好,但它只会删除客人编号为 3 的表 <td>。我的每个按钮看起来像这样 = <button type="button" class="btn btn-danger" onclick="myFunction()" data-value="<% guests[i].guestnumber %>"(注意。这是一个 EJS 页面。)

有没有办法将我的按钮的数据值获取到 fetch 的正文部分,以便每个按钮都可以使用 onclick 函数中的数据值?

【问题讨论】:

    标签: javascript json node.js mongodb mean-stack


    【解决方案1】:

    您没有将值作为参数传递给您的函数,因此您的应用不是动态的,只是静态信息。

    让 guestnumber 等于你的论点。

    function myFunction(id) {
    
        fetch('guests', {
            method: 'delete',
            headers: {
                'Content-Type': 'application/json'
            },
            body: { guestnumber: id }
        })
            .then(res => {
                if (res.ok) return res.json();
            }).
            then(data => {
                console.log(data);
                window.location.reload();
            });
    }
    

    然后在您的 HTML 中将 ejs 放入 onclick 函数中,并将其传递给 myFunction。像这样:

    <button type="button" class="btn btn-danger" onclick="myFunction('<% guests[i].guestnumber %>')" data-value="<% guests[i].guestnumber %>"
    

    【讨论】:

    • 不客气!对答案进行投票并确认其正确是表示赞赏的最佳方式,它可以让其他人更快地找到这个答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2020-10-07
    • 2016-10-31
    • 2017-03-08
    相关资源
    最近更新 更多