简体   繁体   中英

Use Symfony2 route in Javascript

I have a Symfony app using a little bit of Javascript. There is a ajax request calling an API in Symfony:

$.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.

My question is:

What is the best practices to give the JS file my route name in Symfony?

You can use https://github.com/FriendsOfSymfony/FOSJsRoutingBundle to achieve this.

The easiest way would be to return the route from the controller and print in a js variable inside your page:

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

But i wouldn't consider it best practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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