【问题标题】:Symfony2 - Get ID from route to controllerSymfony2 - 从路由到控制器获取 ID
【发布时间】:2015-02-15 00:24:26
【问题描述】:

解决问题有点麻烦。我有一个显示我的数据的 /view-alerts 页面。对于每一行数据,我提供了一个删除选项

<input type="button" value="Delete" data-url="{{ path('NickAlertBundle_delete') }}" onclick="delete_alert( {{ alert[0].id }} )"/>

所以当这个按钮被点击时,一个javascript函数被调用。

function delete_alert(id){
    var answer = confirm("Confirm delete");
    if (answer){
        $.ajax({
            type: "POST",
            url: $(this).attr('data-url'),
            data: {row: id},
            success: function(data) {
                if(data){
                    var splitdata = data.split(":");
                    if(splitdata[0]=="Deleted"){
                        var id = splitdata[1];
                        alert("Your alert has been deleted");
                    }else{
                        alert(data);
                    }
                }else{
                    alert("Unknown Error!");
                }
            },
            error:function(){
                alert("Please try again!");
            }
        });
    }

这会调用我的删除路由,并且应该传递要删除的数据行的 id。我的路线目前是这样的

NickAlertBundle_delete:
    pattern:  /view-alerts
    defaults: { _controller: NickAlertBundle:Alert:delete }
    requirements:
       _method:  POST

我与 view-alerts 具有相同的 url 模式,因为当他们从该页面删除警报时,我不希望他们重定向到另一个页面。

所以现在我正在尝试访问控制器中的 id,以便删除警报。目前我正在尝试

public function deleteAction(Request $request)
{
        $id = $request->get('id');

        $em = $this->getDoctrine()->getManager();
        $alert = $em->getRepository('NickAlertBundle:AvailabilityAlert')->find($id);

        if (!$alert) {
            throw $this->createNotFoundException('Alert not found');
        }

        $alert->setIsDeleted(true);
        $alert->setAlertStatus('Inactive');
        $em->flush();

        return new JsonResponse('Deleted');
}

我目前收到的错误是

查询的标识符 id 缺失 Nick\AlertBundle\Entity\AvailabilityAlert

如何通过我的处理方式(通过 ajax 请求?)将 id 获取到我的控制器?

谢谢

【问题讨论】:

    标签: javascript ajax symfony


    【解决方案1】:

    你试过了吗:

        if($request->isXmlHttpRequest())
                    {
                        $id = (int)$request->request->get('row');
        }
    

    代替:

    $id = $request->get('id');
    

    ?

    【讨论】:

    • 既然请求已经传入控制器,为什么还要从容器中拉取请求呢?我同意,既然参数被称为“行”,那么使用行比 id 更有意义。
    • Cerad 的一个好问题。只是我有使用容器的习惯。你说得对,我编辑了。
    猜你喜欢
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多