douturan1807 2018-07-20 21:47
浏览 61
已采纳

处理Ajax请求Symfony

I am trying to perform an ajax post request but I can't handle the form.

Ajax :

function ft_postFormation(e) {
e.preventDefault();
data = $('form[name=appbundle_formation_post]').serialize();


$.post({
  url: ROOT_DIR + "api/back_office/post_formation",
  data: data,
  contentType: "application/json",
  dataType: 'json',
  beforeSend: function (xhr) {
    xhr.setRequestHeader("Authorization", "Bearer " + $.cookie("token"));
  }
}).done(function (e) {
  console.log(e);
});

} });

controller :

    public function postFormationAction(Request $request)
{
    $formation = new Formation;
    $form = $this->createForm(FormationForm::class, $formation);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid())
    {
        //handling the form
    }
}

}

I don't know if I serialize the data correctly or if I do not handle the form correctly. I read this solution everywhere but I am obviously missing something.

I receive the data within the controller (as a string). I also tried to serialize the form with $.serializeArray() but i could not handle the form either.

In all cases $form->getData says the form is correcly created but not filled with the datas received.

  • 写回答

1条回答 默认 最新

  • doucheng3811 2018-07-21 08:26
    关注

    I've finally found the problem.

    The header was wrong. If you use the serialize() Jquery function, the good header is not dataType:json but dataType:x-www-form-urlencoded. Then, the form is correctly add to the Request object and the form can be handled with $form->handleRequest($form).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Xsheii7我安装这个文件的时候跳出来另一个文件已锁定文件的无一部分进程无法访问。这个该怎么解决
  • ¥15 unity terrain打包后地形错位,跟建筑不在同一个位置,怎么办
  • ¥15 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式
  • ¥15 如果要做一个老年人平板有哪些需求