最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

symfony - How to pass javascript variables values from twig to controller using href path in Symfony2? - Stack Overflow

programmeradmin0浏览0评论

I would like to know how to pass javascript variables values from twig to controller using href path in Symfony2. this is my code:

 <html>
<head>
    <script src="//code.jquery/jquery-1.11.1.min.js"></script>
</head>
<body>
    <script>
        var a = "hello";
        var b = "hi";
        var c = $('<a href="{{ path('ikproj_groupe_homepagegroupe1', {'id': a, 'num': b}) }}">send data</a>');
        $('body').append(c);
    </script>    
</body>
</html>

The problem is that it displays this message: Variable "a" does not exist . So, my question is: what is the correct code to do that?

I would like to know how to pass javascript variables values from twig to controller using href path in Symfony2. this is my code:

 <html>
<head>
    <script src="//code.jquery./jquery-1.11.1.min.js"></script>
</head>
<body>
    <script>
        var a = "hello";
        var b = "hi";
        var c = $('<a href="{{ path('ikproj_groupe_homepagegroupe1', {'id': a, 'num': b}) }}">send data</a>');
        $('body').append(c);
    </script>    
</body>
</html>

The problem is that it displays this message: Variable "a" does not exist . So, my question is: what is the correct code to do that?

Share Improve this question asked Jul 10, 2014 at 9:57 NadimNadim 4041 gold badge11 silver badges32 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

You need to set a twig variable. Ex:

<script>
    {% set a = 'hello' %}
    {% set b = 'hi' %}
    var c = $('<a href="{{ path('ikproj_groupe_homepagegroupe1', {'id': a, 'num': b}) }}">send data</a>');
    $('body').append(c);
</script> 

I find the easiest approach to this is to set the path in the original template using an href (or possible a data) attribute like..

<a href="{{ path('route_name', {'id': a }) }}" 
            class="some-specific-class">Click</a>

Or using a data attribute..

<a href="#" data-href="{{ path('route_name', {'id': a }) }}" 
            class="some-specific-class">Click</a>

And then in the javascript use..

$('a.some-specific-class').on('click', function(e) {
    e.preventDefault();

    var href = $(this).attr('href');
    .. or
    var href = $(this).data('href');

    .. do things with href
});

Alternatively you could you the FOSJSRoutingBundle and pass the id in a data attribute and generate the route from that using..

$('a.something').on('click', function(e) {
    e.preventDefault();

    var id = $(this).data('id'),
        url = Routing.generate('rout_name', {'id': id });

    .. do stuff with url
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论