通过ajax从数据库中删除一行

时间:2012-10-24 21:12:47

标签: ajax jquery symfony

我有这个javascript函数来删除行但功能不起作用

$(document).ready(function()
{
    $('table#example td a.delete').click(function()
    {
        if (confirm("Are you sure you want to delete this row?"))
        {
            var id = $(this).parent().parent().attr('id');
            var data = 'id=' + id ;
            var parent = $(this).parent().parent();

            $.ajax(
            {
                   type: "POST",
                   url: "supprimerkpi",
                   data: data,
                   cache: false,

                   success: function()
                   {
                        parent.fadeOut('slow', function() {$(this).remove();});

                        // sets specified color for every odd row
                        $('table#example tr:odd').css('background',' #FFFFFF');
                   }
             });
        }
    });

在我的网页html中:

<a href="#" class="delete" style="color:#FF0000;">

在我的控制器中

$repository = $this->getDoctrine()->getEntityManager()->getRepository('AdminBlogBundle:Condkpi'); $id=$this->getRequest()->query->get('id');
$em = $this->getDoctrine()->getEntityManager();
$uti=$repository->findOneBy(array('id' => $id));
$em->remove($uti);
$em->flush();

2 个答案:

答案 0 :(得分:0)

您通过POST方法发送“id”。所以,你需要改变:

$id=$this->getRequest()->query->get('id');

成:

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

另外,你可以改变:

$uti=$repository->findOneBy(array('id' => $id));

成:

$uti=$repository->find($id);

.. as find()使用主键搜索实体...

另一方面,什么是“supprimerkpi”?这不是有效的目标网址,对吧? :)

答案 1 :(得分:0)

routing.yml

delete_data:
    path:     /delete
    defaults: { _controller: AcmeDemoBundle:Default:delete}

在您的ajax调用url参数中根据此

更改
var id = $(this).parent().parent().attr('id');

var data = 'id=' + id ;


 var parent = $(this).parent().parent();

        $.ajax(
        {
               type: "POST",
               url: "{{ path('delete_data') }}",
               data: {id :id },
               cache: false,

               success: function()
               {
                    parent.fadeOut('slow', function() {$(this).remove();});

                    // sets specified color for every odd row
                    $('table#example tr:odd').css('background',' #FFFFFF');
               }
         });

AcmeDemoBundle/Controller/DeafultControlller.php

public function deleteAction(Request $request)
{
   $id = $request->get('id');
   $repository = 
    $this->getDoctrine()->getEntityManager()->getRepository('AdminBlogBundle:Condkpi'); 
   $em = $this->getDoctrine()->getEntityManager();
   $uti=$repository->findOneById($id);
   $em->remove($uti);
   $em->flush();
}