dongma0722
2015-06-24 13:40
浏览 57
已采纳

Symfony2将变量从控制器传递给javascript

I have this controller.php

    $repository = $this->getDoctrine()->getManager()->getRepository('TechappStatsBundle:ParentForm');
    $data = $repository->findBy(array(),array('id' => 'desc'),1,0); 

    $formulaire = new ParentForm();

    $parent= $this->get('form.factory')->create(new ParentFormType(),$formulaire);

    if ($parent->handleRequest($request)->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($formulaire);
        $em->flush();
    }

    return $this->render('TechappStatsBundle:Stats:index.html.twig',array("res" => $data,
        "parentform"=>$parent->createView(),));

I want to check the variable res in my view with js if it is equals to a specific value or not but I don't know how to pass it.

图片转代码服务由CSDN问答提供 功能建议

我有这个controller.php

  $ repository = $ this-> getDoctrine() - > getManager() - > getRepository('TechappStatsBundle:ParentForm'); 
 $ data = $ repository-> findBy(array()  ,array('id'=>'desc'),1,0);  
 
 $ formulaire = new ParentForm(); 
 
 $ parent = $ this-> get('form.factory') - > create(new ParentFormType(),$ formulaire); 
 
  if($ parent-> handleRequest($ request) - > isValid()){
 $ em = $ this-> getDoctrine() - > getManager(); 
 $ em-> persist($ 公式); 
 $ em-> flush(); 
} 
 
返回$ this-> render('TechappStatsBundle:Stats:index.html.twig',array(“res”=> $ 数据,
“parentform”=> $ parent-> createView(),)); 
   
 
 

我想检查变量 res < / code>在我的视图中使用js,如果它等于某个特定值,但我不知道如何传递它。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dqg63264 2015-06-24 14:19
    已采纳

    You can pass the parameters from controller like:

    return $this->render('TechappStatsBundle:Stats:index.html.twig', array(
                    "res" => "Your data here"));
    

    And you can access the "res" parameter in index.html.twig like:

    {% block js %}
     <script type="text/javascript">
    var res = '{{ res }}';
    alert(res);
    </script>
    {% endblock %}
    
    已采纳该答案
    打赏 评论
  • dongrou839975 2015-06-24 13:56

    If you want to pass data to Javascript, you can update your view to either:

    • Add an hidden input (if this is a form) that contains the value of the data
    • Add data to a DIV or P (or whatever) that you hide with CSS
    • Add an attribute to a specific field, for example data-<field>

    Once you get it, you can easily fetch the value from jQuery.

    打赏 评论
  • duanbei3747 2015-06-24 14:38

    My option always is send it in a data-value,

    You can do something like

    <div id="res-result" data-res="{{ res }}" style="display: none;">
    

    The div doesn't need to be hidden, if it's something related with a div I always put it inside the div related, even if it's not hidden

    And then from Jquery:

    resValue = $('#res-result').data('res');
    

    Having the JS file outside of the HTML is the cleanest way IMO

    打赏 评论

相关推荐 更多相似问题