如何将循环数据库变量放入jQuery函数

时间:2019-02-11 22:48:44

标签: php jquery

这肯定是一个显而易见的答案,但我找不到任何地方。

我使用php为数据库中的每一行生成一个结果表。每个表行都有一个删除按钮,该按钮基于值“ custref”删除数据库行。我想弹出一条警报以进行确认,然后再带您执行删除查询,但是我正在努力通过jquery警报将custref值传递到删除页面。如果我将jquery放在头部,则它在while循环之外,因此不会收到custref值。如果我将其放入循环中,它将被多次调用并且无法正常工作。

在头部:

 // show an alert before deleting
$('.delete').on('click', function(){
    $.confirm({
        title: 'Deleting Customer!',
        content: 'Are you sure?',
        type: 'red',
        buttons: {
            tryAgain: {
                text: 'Delete',
                btnClass: 'btn-red',
                action: function(){
                    location.href='actions/delete-enquiry.php?custref=$custref';
                }
            },
            close: function () {
            }
        }
    });
});

在php while循环中:

$custref = $row["custref"];

<input type='button' class='delete' value='DELETE' />

这实际上是输出custref = $ custref而不是与行相关的值

1 个答案:

答案 0 :(得分:0)

如果每个客户都有自己的删除按钮,则可以将onclick属性设置为接受参数的函数,在这种情况下为客户参考。

  

此示例同时使用JQuerySweet Alert插件。

创建删除按钮的PHP示例:

$Customers = Array("1", "2", "3", "4", "5");
ForEach ($Customers AS $Customer) {
    Echo "<input type='button' onclick='deleteCustomer(\"$Customer\");' class='delete' value='DELETE $Customer' /><br /><br />";
}

JQuery代码以显示确认对话框,然后处理是否为真:

function deleteCustomer(CustomerRef) {
    Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.value) {
            Swal.fire(
                'Deleted!',
                'Customer number ' + CustomerRef + ' has been deleted.',
                'success'
            )}
        // Redirect to your deletion script. Could also use AJAX
        location.href='actions/delete-enquiry.php?custref=' + CustomerRef;
    })
}

有关示例,请参见here