Symfony3发送AJAX POST请求


Symfony3 send AJAX POST request

我想通过AJAX POST请求发送两个变量idcommence。问题是我没有得到POST变量,但是到达了路由。

JS:

$.post(Routing.generate('ajax_savecommentary', { id:id, commentary:commentary }), 
function(response)
{
}, "json");

Symfony:

public function saveCommentaryAction()
{
    if (!$this->get('session')->get('compte'))
        return $this->redirect($this->generateUrl('accueil'));
    $request = $this->container->get('request_stack')->getCurrentRequest();
    $isAjax = $request->isXMLHttpRequest();
    if ($isAjax)
    {
        $information = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Information')->find($_POST['id']);
        $information->setCommentaire(str_replace(''n', '''n', $_POST['commentary']));
        $this->getDoctrine()->getManager()->flush();
        $response = array("code" => 100, "success" => true, 'commentary' => $_POST['commentary']);
        return new Response(json_encode($response));
    }
    $response = array("code" => 0, "success" => false);
    return new Response(json_encode($response));
}

错误:

http://localhost/MyProject/web/app_dev.php/ajax/save/commentary/?id=61&comment=我的评论。

{"code":0,"success":false}

更多Symfony错误:

GET Parameters
Key/Value
commentary/MyCommentary
id/61

路由是必要的情况:

ajax_savecommentary:
    defaults: { _controller: CommonBundle:Default:saveCommentary }
    path:     /ajax/save/commentary/
    options:
        expose: true

尝试使用传递给控制器操作的请求,而不是从容器中检索它。所以试试这个:

use Symfony'Component'HttpFoundation'Request;
...
public function saveCommentaryAction(Request $request)
{
    if (!$this->get('session')->get('compte'))
        return $this->redirect($this->generateUrl('accueil'));
    $isAjax = $request->isXMLHttpRequest();

而不是这个:

public function saveCommentaryAction()
{
    if (!$this->get('session')->get('compte'))
        return $this->redirect($this->generateUrl('accueil'));
    $request = $this->container->get('request_stack')->getCurrentRequest();
    $isAjax = $request->isXMLHttpRequest();

更新:

您可以使用带有条件的自定义路线匹配来限制您的路线,例如您的案例如下:

ajax_savecommentary:
    defaults: { _controller: CommonBundle:Default:saveCommentary }
    path:     /ajax/save/commentary/
    options:
        expose: true
    condition: "request.isXmlHttpRequest()"
    methods:  [POST]

更新:

JS端的路由生成中有一个拼写错误:

$.post(Routing.generate('ajax_savecommentary', { id:id, commentary:commentary }), 
function(response)
{
}, "json");

您将数据作为routing.generate函数的参数传递,以便它将参数连接为查询字符串。所以试试这个:

$.post(Routing.generate('ajax_savecommentary'), { id:id, commentary:commentary }, 
function(response)
{
}, "json");

另一个建议是使用$request对象来获取数据,而不是使用超全局PHP属性,因此使用:

$request->request-get('commentary');

而不是:

 $_POST['commentary']

更多信息请参阅文档。

希望这能帮助