Symfony:通过GET将变量发送到Ajax的处理程序


Symfony: Send variable throught GET to handler from Ajax

我想在我的Symfony3.0.3项目中使用AJAX。通信有效,但我无法从 JS 获取变量到处理程序。在 JS 的方向处理程序中,它工作正常。

我试图从带有"$request->query->get('id'))"的请求中获取变量,但我只得到"null"。

以另一种方式,我尝试使用URL中的变量,但出现此错误:

"在

呈现模板期间引发了异常("缺少一些必需参数("id")来生成路由"admin_ajax"的 URL。在 CommonBundle:Default:index.html.twig 中,第 421 行。

我不介意使用解决方案或其他解决方案(根据您的建议,我会使用最好的解决方案),但我仍然希望这两个错误的解决方案。

.JS

function selectClient(idClient)//idClient = 1
{
    alert(idClient);
    $.post('{{path('admin_ajax')}}',{idClient: id}, 
            function(response)
            {
                if(response.code == 100 && response.success)
                {
                    alert(response.id);//Show null if using $request->query->get('id')) in handler but should be 1
                }}, "json");    
}

路由:

admin_ajax:
    defaults: { _controller: CommonBundle:Default:getClient }
    path:     /ajax/{id}

处理器:

public function getClientAction($id)
{
    $request = $this->container->get('request_stack')->getCurrentRequest();
    $isAjax = $request->isXMLHttpRequest();
    if ($isAjax)
    {
        $response = array("code" => 100, "success" => true, "id" => $request->query->get('id'));
        return new Response(json_encode($response));
    }
    $response = array("code" => 0, "success" => false);
    return new Response(json_encode($response));
}

编辑:感谢 Rim,Rvanlaak 的回答,我使用了 FOSJsRoutingBundle。

.JS

function selectClient(idClient)
{
    $.get(Routing.generate('ajax_getclient', { id:idClient }), 
            function(response)
            {
                if(response.code == 100 && response.success)
                {
                    alert(response.id);
                }
                else
            }, "json");
}

路由:

ajax_getclient:
    defaults: { _controller: CommonBundle:Default:getClient }
    path:     /ajax/{id}
    options:
        expose: true

请注意,选项"expose: true"是工作所必需的。

这是因为树枝在javascript之前执行,所以他没有重新协调客户端ID参数

我遇到了同样的问题,并使用FOSJSRoutingBundle解决了它,请参阅这篇文章:

Ajax url parametetr using Twig path