简体   繁体   English

在Javascript中使用Symfony2路由

[英]Use Symfony2 route in Javascript

I have a Symfony app using a little bit of Javascript. 我有一个使用一点Javascript的Symfony应用程序。 There is a ajax request calling an API in Symfony: 有一个ajax请求在Symfony中调用API:

$.ajax({
    type: "POST",
    url: "http://symfony.dev/api/price",
    cache: false,
    data: {
        'volume': $('#tunnel_step_one_volume').val(),
        'delivery': $('#tunnel_step_one_isStandardDelivery').val()
    },

    success: function (data, status) {
        console.log(data);
        Command.refreshData(data);
    },

    error: function (jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
    }
})

Now the URL is hard coded. 现在,URL已被硬编码。

My question is: 我的问题是:

What is the best practices to give the JS file my route name in Symfony? 在Symfony中为JS文件指定路由名称的最佳实践是什么?

You can use https://github.com/FriendsOfSymfony/FOSJsRoutingBundle to achieve this. 您可以使用https://github.com/FriendsOfSymfony/FOSJsRoutingBundle来实现。

The easiest way would be to return the route from the controller and print in a js variable inside your page: 最简单的方法是从控制器返回路由并在页面内的js变量中打印:

<script> myUrl = {{myUrl}} </script>

But i wouldn't consider it best practice. 但是我不认为这是最佳实践。

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

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