在symfony项目中使用ajax来删除项目

问题描述 投票:-1回答:1

你好我正在寻找一个脚本,可以让我使用ajax删除symfony项目中的项目,我没有找到任何解决方案,我试图通过id删除项目(我给了一个静态ID),然后得到没有刷新页面的结果是我的控制器

$em = $this->getDoctrine()->getManager();
$evenement = $em->getRepository("TunisiaMallBundle:Evenement")->find(39);
$em->remove($evenement);
$em->flush();
$evenements = $em->getRepository("TunisiaMallBundle:Evenement")->findAll();
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($evenements));
return $response;

我不知道我应该归还什么。 image

javascript php ajax symfony twig
1个回答
1
投票

在你的树枝上放这样的东西:

<button class="deleteBtn" id="{{ item.id }}">Remove</button>

这是使用JQuery的ajax:

$(document).ready(function(){

$('.deleteBtn').click(function (e) {
    e.preventDefault();

    itemId = $(this).attr('id');

    $.ajax({

        url: frm.attr('action'),
        data: {'entityId':itemId},
        method: 'post',
        success: function (data, reponse) {

         if(reponse == 'good' ){
            //appear pop to say success blabla
         }
        },
        error: function () {
            //appear pop to say error blabla
        },
    });

});

和控制器:

public function ajaxDeleteItemAction(Request $request)
{

    if($request->isXmlHttpRequest()){
    $id = $request->get('entityId');
    $em = $this->getDoctrine()->getManager();
    $evenement = $em->getRepository("TunisiaMallBundle:Evenement")-
    >find($id);

   $em->remove($evenement);
   $em->flush();


    return new JsonResponse('good');
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.