这是我的app / routing.yml
FrontendBundle:
resource: "@FrontendBundle/Resources/config/routing.yml" prefix: /{_locale}/ requirements: _locale: en|es
BackendBundle:
resource: "@BackendBundle/Resources/config/routing.yml" prefix: /{_locale}/app requirements: _locale: en|es
fos_js_routing: 资源:" @ FOSJsRoutingBundle / Resources / config / routing / routing.xml"
这是我的BackendBundle \ Resources \ Config \ routing.yml
getModelsFromMake:
pattern: /getModelsFromMake/{idMake} defaults: { _controller: BackendBundle:Backend:getModelFromMake } options: expose: true
我的问题是当我这样做一个ajax调用时:
铬检查员告诉我:$。AJAX({ 键入:" POST",
url: Routing.generate('getModelsFromMake'), data: { idMake: $('#make').val(), }, dataType: "json", success: function(data) { console.log("All OK"); }, error: function() { console.log("ERROR"); } });
Uncaught Error: The route "getModelsFromMake" requires the parameter "_locale".
有什么想法解决这个问题吗?
编辑1:
在我的布局中我有这个:
<script type="text/javascript" src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script> <script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>
编辑2:
如果我运行命令&#34; php app / console fos:js-routing:debug&#34;我明白了:
Name Method Pattern
getModelsFromMake ANY /{_locale}/app/getModelsFromMake
答案 0 :(得分:4)
要将请求区域设置设置为您对Routing.generate的所有调用,您可以覆盖此方法并在每次调用中添加{{app.request.locale}}参数。必须在twig模板中执行以下脚本,并在包含路由脚本之后执行。
<!-- Include JSRouting libs & exposed routes -->
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>
<script>
$(function () {
// change name of initial method
Routing.generateImpl = Routing.generate;
// override generate fonction by adding a default _locale from request locale
Routing.generate = function (url, params) {
var paramsExt = {};
if (params) {
paramsExt = params;
}
if (!paramsExt._locale){
paramsExt._locale = '{{ app.request.locale }}';
}
return Routing.generateImpl(url, paramsExt);
}
})
</script>
现在您可以透明地使用Routing.generate而无需担心_locale参数!
// in any JS file
var url = Routing.generate('mypath');
var url2 = Routing.generate('another path', {param: 1});
为了澄清代码,可以在js文件中隔离以前的脚本。为此,全局变量必须由@DonCallisto定义。
<!-- for exemple in the <head> of the page -->
<script>
var REQUEST_LOCALE = '{{ app.request.locale }}';
</script>
在脚本中你可以使用REQUEST_LOCALE
// this line
paramsExt._locale = '{{ app.request.locale }}';
// has to be replaced by
paramsExt._locale = REQUEST_LOCALE;
答案 1 :(得分:2)
尝试在您的ajax
之前插入此代码段<script>
var locale= {{ app.request.locale }} ;
</script>
并按如下所示修改您的脚本
$.ajax({ type: "POST",
url: Routing.generate('getModelsFromMake', array('_locale' => locale)),
data: {
idMake: $('#make').val(),
},
dataType: "json",
success: function(data) { console.log("All OK"); },
error: function() { console.log("ERROR"); }
});