How to make a POST Ajax request with Symfony and Jquery

后端 未结 2 832
南方客
南方客 2021-02-01 07:11

I need to store some map parameter in my symfony project, to do this i need to implement some Ajax in my view which will be able to pass some info to the controller.

I r

2条回答
  •  心在旅途
    2021-02-01 07:51

    Try this,

    /**                                                                                   
     * @Route("/ajax", name="_recherche_ajax")
     */
    public function ajaxAction(Request $request)    
    {
        if ($request->isXMLHttpRequest()) {         
            return new JsonResponse(array('data' => 'this is a json response'));
        }
    
        return new Response('This is not ajax!', 400);
    }
    

    In case of you sending an Ajax request, you need to return json/plaintext/xml data, and not a whole Response object.

    PS: Do not forget to add use statment for Request and JsonResponse

    EDIT : As the error message you added says, you need to import the annotation @Method by using :

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

提交回复
热议问题