简体   繁体   English

无法使用POST方法Symfony3将数据发送到控制器

[英]Can't send data to the Controller with a POST method Symfony3

I have a POST method Jquery. 我有一个POST方法Jquery。 Ajax and I can't send my data to the controller, I have tried every solution on the net, but no result....... Ajax和我无法将数据发送到控制器,我已经尝试了网络上的所有解决方案,但没有结果.......

My JavaScript 我的JavaScript

  $(document).ready(function(){
        $('#submitForm').click(function(){

            var data1 = {request : $('#request').val()};
            $.ajax({
                type: "POST",
                url: "/Manufacturer",
                data: data1,
                success: function(dataBack) {
                    console.log(dataBack);

                },
                contentType: "application/json",
                dataType: 'json'
            });
        });
    });

MY controller 我的控制器

public function indexAction(Request $request)
{
    //$name = $request->request->get('data');
    //return new Response($name);//or do whatever you want with the sent value
    if($request->isXmlHttpRequest()){
        $name = $request->request->get('data1');
        If($name == 1)
        {
            return new Response('Yeap');
        }
        else
        {
            return new Response(';(');
        }

    }
    return $this->render('MyIndex/Manufacturer_LIST.html.twig' );
}

HEre is my Console :: 这是我的控制台::

And my response is as it's obvious ";(" 我的回答很明显是“;(”

First you need to install FOSJsRoutingBundle to be able to "expose" your Symfony routes into the javascript code. 首先,您需要安装FOSJsRoutingBundle才能将您的Symfony路由“公开”到javascript代码中。 Follow the steps in the official documentation. 请遵循官方文档中的步骤。

Then, in your twig template if you have a form like: 然后,在树枝模板中,如果您具有如下形式:

<form>
    <input type="text" id="name"> <br>
    <button type="submit" id="submitForm">Submit</button>
</form>

your js code could look liks this: 您的js代码可能看起来像这样:

$('#submitForm').click(function(e){
    e.preventDefault();
    var name = $('#name').val();
    $.ajax({
        method: 'POST',
        url: Routing.generate('Manufacturer_LIST');
        // OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
        data: { name:name }
    }).done(function(msg){
        console.log(msg);
    }).fail(function(XMLHttpRequest, textStatus, errorThrown){
        console.log(textStatus + ' ' + errorThrown);
    });
});

And in your controller: 在您的控制器中:

/**
 * @Route("/Manufacturer", name="Manufacturer_LIST", options={"expose"=true})
 */
public function indexAction(Request $request){
    if($request->isXmlHttpRequest()){
        $name = $request->request->get('name');
        return new Response($name);//or do whatever you want with the sent value
    }
    return $this->redirectToRoute('homepage');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM