将视图作为数据传递给symfony中的js

时间:2014-01-21 09:03:43

标签: javascript symfony

我尝试使用java脚本在索引页面中实现搜索功能。我有一个表单输入名称,当应用serach时,索引页面将更新并加载带有搜索结果的新索引页面

以下是我的索引页面中的表单

<div id="content">
  <form id="myForm" action="{{path('index_search')}}" method="POST" >
    Write your name here: 
    <input type="text" name="name" id="name_id" value="" /><br />
    <input type="submit" value="Send" />
  </form>
 </div>
<div id="output">#current index</div>

这是行动执行

public function searchAction()
       {
       $request = $this->get('request');
       $name=$request->request->get('formName');

            $em = $this->getDoctrine()->getManager();
            $entities = $em->getRepository('SystemVmsBundle:VisitorsDetails')->findOneByfirstname($name);

            $view = $this->render('SystemVmsBundle:VisitorsDetails:index.html.twig',array(
                'entities' => $entities,
            ));
            $return=array("responseCode"=>200,  "view"=>$view);

            $return=json_encode($return);//jscon encode the array
       return new Response($return,200,array('Content-Type'=>'application/json'));
}

这是js

  $(document).ready(function() {

   //listen for the form beeing submitted
   $("#myForm").submit(function(){
      //get the url for the form
      var url=$("#myForm").attr("action");

       $.post(url,{
           formName:$("#name_id").val(),
           other:"attributes"
       },function(data){
           //the response is in the data variable

            if(data.responseCode==200 ){
                $('#output').html(data.view);

                $('#output').css("color","red");
            }
           else{

              alert("An unexpeded error occured.");


           }
       });
      return false;
   });


   });

但是我的js正在工作,但无法将数据作为视图传递给js.How如何将视图'index.html.twig'传递给js?

当用萤火虫检查时,我得到了

{"responseCode":200,"view":{"headers":{}}}

任何想法?提前致谢!

1 个答案:

答案 0 :(得分:0)

尝试在$ .post函数上指定dataType,如下所示:

$.post(url, {formName: $("#name_id").val(), other: "attributes"}, 
  function(data) {
    if(data.responseCode == 200){
      $('#output')
        .html(data.view)
        .css("color","red");
    } else {
      alert("An unexpeded error occured.");
    }
  }, 'json');

但是如果你只需要html,而不是json中的其他数据,你应该改变逻辑,渲染一个普通模板并使用dataType'html'。是这样的:

// ...Controller.php
$view = $this->render('SystemVmsBundle:VisitorsDetails:index.html.twig',array(
    'entities' => $entities,
));
return new Response($view);

// index.html.twig
$.ajax({
  url: url,
  dataType: 'html',
  type: 'POST',
  data: {formName: $("#name_id").val(), other:"attributes"},
  success: function (data) {
    $('#output').html(data).css("color","red");
  }
});