Symfony 删除 ajax

Symfony delete ajax

当我想在模板 Twig 中使用 Ajax 和 Symfony 删除寄存器时遇到问题。

<tbody>
    {% for entity in entities %}
        <tr>
            <td>
                <a class="delete btn btn-danger btn-xs glyphicon glyphicon-trash" data-playgroup-id="{{ entity.id }}" ></a>
            </td>
        </tr>
    {% endfor %}
</tbody>

Ajax:

$(document).ready(function() {

    $(".delete").click(function(){
        var pid = $(this).attr("data-playgroup-id");

        bootbox.confirm("Are you sure?", function(result) {
            if(result){
                $.ajax({ 
                    url: '{{path('playergroup_delete', { 'id': pid}) }}',
                    type: 'delete', 
                    success: function(result) {
                        console.log('Delete');
                    },
                    error: function(e){
                        console.log(e.responseText);
                    }
                });
            }
        });
    });
});

我收到下一个错误:

变量"pid"不存在。

谢谢!

这意味着您没有将 pid 变量传递给您的 Twig 模板。

通过控制器传递它就可以了

错误是:

您正在尝试在您的 Twig 模板(服务器端)中设置来自客户端 (javascript) 的变量。

正如 Mourad 所说,您在 twig 函数(服务器端)中传递了一个变量,并且您正在使用 javascript(客户端)获取该变量。 要解决这个问题,请执行以下操作:

$(document).ready(function() {

    $(".delete").click(function(){
        var pid = $(this).attr("data-playgroup-id");

        bootbox.confirm("Are you sure?", function(result) {
            url = '{{path('playergroup_delete', { 'id': 0}) }}';
            url = $url.replace("0",pid);
            if(result){
                $.ajax({ 
                    url: url,
                    type: 'delete', 
                    success: function(result) {
                        console.log('Delete');
                    },
                    error: function(e){
                        console.log(e.responseText);
                    }
                });
            }
        });
    });
});