【问题标题】:Delete table row (from a loop an api) by using curl使用 curl 删除表行(从循环一个 api)
【发布时间】:2018-03-07 17:12:20
【问题描述】:

我正在使用 for 循环在表格中显示来自 API 的数据:

for ($i = 0; $i < count($return['data']); $i++){
    echo "<tr><td>".$return['data'][$i]['data_id']."</td>";
    echo "<td>".'<button id="delete" class="btn btn-danger" value="'.$return['data'][$i]['data_id'].'" type="text">Delete</button>'."</td></tr>";
}

结果是一个表格,其中连续显示data_id 和删除按钮。现在,我希望能够在单击删除按钮时通过将data_id 发送到curl-&gt; delete (API) 代码来删除该项目! 或者在单击的删除按钮上运行下面的代码。

curl --include \ --request DELETE \ --header "<secret key>" \ https://example.com/api/v1/data/{data_Iid}?app_id={appId}

我需要从循环中包含data_id 并将其传递给简单的删除代码。我使用onClick 函数来获取data_id 的值,但它只显示每个删除按钮的第一个data_id 值。

我怎样才能实现我的目标,并且能够通过正确的data_id 来 curl 删除代码?

谢谢。

【问题讨论】:

    标签: javascript php jquery api curl


    【解决方案1】:

    出于性能原因,我会在桌面上放置一个事件侦听器。一个 JavaScript 事件侦听器可以捕获按钮上的所有点击。看看下面的例子。

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>Button Value Event Listener</title>
        </head>
        <body>
            <table id="my-table">
            <thead>
                <tr>
                    <th>Spalte 1</th>
                    <th>Spalte 2</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Wert 1</td>
                    <td>
                        <button value="1" name="delete[]">Mein Button</button>
                    </td>
                </tr>
                <tr>
                    <td>Wert 2</td>
                    <td>
                        <button value="2" name="delete[]">Mein Button</button>
                    </td>
                </tr>
            </tbody>
            </table>
            <script>
                var table = document.getElementById('my-table');
                table.addEventListener('click', function(event) {
                    var target = event.target;
    
                    if (target.tagName = 'BUTTON' && target.value) {
                        // remove and place your ajax request here
                        console.log(target.value);
                    }
                });
            </script>
        </body>
    </html>
    

    通过这个示例,您将获得在 for 循环中为按钮放置的所有值。请确保 $return['data'][$i]['data_id'] 已设置并包含您期望的值。

    在 given 示例中,您的 id 刚刚登录到控制台。请用您的异步 javascript 请求 (AJAX) 替换 console.log

    【讨论】:

    • 好的,我做到了,而且我在 ajax 上运行错误,你能帮我解决这个问题吗?这是我在 if:` if (target.tagName = 'BUTTON' && target.value) {$.ajax({url:"delete.php", data: $(this).target.value, type : POST", dataType: "json", success: function (data) { $('#resultback').addClass("alert alert-success").html('已经取消成功!'); } }); }`
    猜你喜欢
    • 2010-12-15
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    相关资源
    最近更新 更多