【问题标题】:load view using ajax symfony2使用 ajax symfony2 加载视图
【发布时间】:2012-03-01 12:40:05
【问题描述】:

我对 symfony2 非常陌生,当用户单击 div 时,我在使用 ajax 加载视图时遇到了一些问题。使用 firebug 我可以看到数据已返回,但我无法将结果附加到页面中。

我的代码: //默认控制器

public function indexAction($num, Request $request)
    {
        $request = $this->getRequest();

        if($request->isXmlHttpRequest()){
            $content = $this->forward('PaginationBundle:Default:ajax');
           $res = new Response($content);
            return $res;
        } 

        return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
    }

        public function ajaxAction()
    {
        return $this->render('PaginationBundle:Default:page.html.twig');
    }
}

我的 Js: 点击#target时,我想在我的div中加载page.html.twig

$("div#target").click(function(event){
    t = t +1;
    $.ajax({
       type: "POST",
       cache: "false",
       dataType: "html",
       success: function(){
       $("div#box").append(data);    
       }
    });
  });

我在控制器中使用 isXmlHttpRequest() 来检测是否是加载 ajaxAction 的 ajax 请求。我得到了关于萤火虫的观点,但它没有附加在我的 div#box 中。 div#box 存在于 index.html.twig 中

提前谢谢大家

【问题讨论】:

  • 你为什么要做$request = $request->getRequest()? $request 已经设置好了。
  • 谢谢,我还有点困惑,我需要仔细阅读文档

标签: javascript jquery


【解决方案1】:

在你的 $("div#target").click(function(event) 事件你没有在ajax调用中指定url参数,另一件事是你必须在'success'中指定一个参数 ajax调用的参数。

$("div#target").click(function(event){
    t = t +1;
    $.ajax({

       type: "POST",
       url: "{{path('yourpath-means header name in routing.yml')}}",
       cache: "false",
       dataType: "html",
       success: function(result){
       $("div#box").append(result);    
       }
    });
  });

希望这会有所帮助... 快乐编码

【讨论】:

    【解决方案2】:

    这与 symfony 无关,而是与您的 ajax 选项有关。不过 Pece 是对的:您可以直接使用 §this->forward 的返回,因为它是一个 Response 对象。

    问题在于您的 ajax 选项。您必须在内部函数中传递数据对象,否则数据只是空值。试试这个:

    success: function(data){
        $("div#box").append(data);    
    }
    

    【讨论】:

      【解决方案3】:

      我没有让您转发处理 AJAX 调用。试试这个:

      if($request->isXmlHttpRequest()){
          return $this->forward('PaginationBundle:Default:ajax');
      }
      

      Controller::forward() 已经返回了一个 Response 对象;)

      【讨论】:

      • 这种方式好多了,我可以得到更少清晰的代码。多谢 !我试过这样: $this->render('PaginationBundle:Default:page.html.twig');并且运作良好。
      猜你喜欢
      • 1970-01-01
      • 2015-12-17
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多