简体   繁体   English

Symfony2控制器和Javascript参数传递

[英]Symfony2 controller and Javascript argument passing

I am developing an application using symfony2. 我正在使用symfony2开发应用程序。 I would like to know how I can receive arguments from a template in a controller because I want to store the value of the argument in the data base. 我想知道如何从控制器中的模板接收参数,因为我想将参数的值存储在数据库中。 The argument will get its value in a JavaScript script inside the template and must be passed to the controller when submitting a button. 参数将在模板内的JavaScript脚本中获取其值,并且在提交按钮时必须将其传递给控制器​​。 This is the script: 这是脚本:

$("MatchedTag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;  

 }); 

The variable I want to receive in the controller is IdOfTag. 我要在控制器中接收的变量是IdOfTag。 How can I do this? 我怎样才能做到这一点? Thanks. 谢谢。

In our applications we use two approaches. 在我们的应用程序中,我们使用两种方法。

First approach 第一种方法

First approach is to create the "configuration" file in twig, that would be included somewhere in header. 第一种方法是在树枝中创建“配置”文件,该文件将包含在标头中的某个位置。 This file contains all JS variables you would need in the script. 该文件包含脚本中需要的所有JS变量。 These values of these variables are passed from the controller. 这些变量的这些值从控制器传递。 Then in twig template of the "parameters" file you simply add them in appropriate places: 然后,在“参数”文件的树枝模板中,只需将它们添加到适当的位置即可:

   <script>
       myObj.var = "{{ var_from_controller }}";
   </script>

Second approach 第二种方法

Another approach is to put needed variables into additional custom attributes of html tag. 另一种方法是将所需的变量放入html标记的其他自定义属性中。 We usually do it, when we need to take certain route. 我们通常在需要采取某些路线时这样做。

   <p id="myDataHolder" data-src="{{ path('MyUserBundle_ajax_route') }}">blah</p>

And then, in your JS you just parse an attribute of that tag. 然后,在您的JS中,您只需解析该标签的属性。

You can pass the variable using AJAX (take a look at $.ajax , $.post , $.get - jQuery) or add a hidden input field to form with the desired value. 您可以使用AJAX传递变量(看看$ .ajax$ .post$ .get -jQuery)或添加隐藏的输入字段以形成具有所需值的表单。

Example

If you want to pass IdOfTag to /path/controller/tags (as example) using jQuery.ajax your code will looks like this: 如果您想使用jQuery.ajax将IdOfTag传递到/path/controller/tags (例如),您的代码将如下所示:

$("MatchedTag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;  
       $.ajax({
          url: "/path/controller/tags",
          type: "POST",
          data: { "tag_id" : idOfTag },
          success: function(data) {
             //(success) do something...
             //variable "data" contains data returned by the controller. 
          }
       });
});

Then in the controller you can get the value of idOfTag through $_POST["tag_id"] 然后,在控制器中,您可以通过$_POST["tag_id"]获得idOfTag的值

Good look and check the links above. 外观不错,请检查上面的链接。

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

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