使用Ajax Post将数据发送到Symfony2控制器

时间:2014-07-03 10:07:23

标签: php ajax symfony

如果有人播放YouTube视频,我想将此信息发送给Symfony控制器。但不知怎的,控制器什么也没收到。

Ajax Post

 // Check if video is playing (works)
  var myPlayerState;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
        alert('playing');

         $.ajax({
              url: "{{ path('dbe_user_add_experience') }}",
              type: "POST",
              data: { "data" : 'test' },
              success: function(data) { 
                 alert (data);
              },
              error: function(XMLHttpRequest, textStatus, errorThrown)
              {
                alert('Error: ' +  errorThrown);
              }
           });
    }
    myPlayerState = event.data;
  }

路由

<route id="dbe_user_add_experience" pattern="/getexperience">
    <default key="_controller">FOSUserBundle:Level:getExperience</default>
</route>

控制器

  public function getExperienceAction(){
        $request = $this->container->get('request');
        $data = $request->request->get('data');
        var_dump($data);
        die;


        $url = $this->container->get('router')->generate('fos_user_profile_show');
        $response = new RedirectResponse($url);
        return $response;

        //$this->addExperience(5);
  }

3 个答案:

答案 0 :(得分:1)

而不是

$data = $request->query->get('data');

使用

$data = $request->get('data');

答案 1 :(得分:1)

您使用了错误的属性来获取POST数据。

获取GET数据:

$request->query->get('data');

获取POST数据:

$request->request->get('data');

来自http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Request.html

答案 2 :(得分:0)

我发现了错误: 阿贾克斯处于noconflict模式。这意味着我必须将$.ajax({更改为jQuery.ajax({