javascript - Symfony 表单 AJAX 返回空对象

标签 javascript php ajax forms symfony

我正在尝试使用 Symfony 创建 AJAX 表单,但我的表单返回空对象。当我发送手动写入的文本或数组时,一切正常。错误在哪里?我的表单出了问题,还是 javascript 代码有问题?

/**
* Renders the "new" form
* 
* @Route("/", name="demo_new")
* @Method("GET")
*/
public function newAction(Request $request) {
    $entity = new Demo();
    $form = $this->createForm(DemoType::class, $entity);

    return $this->render('default/new.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView()
            )
    );
}

/**
*
* @Route("/", name="demo_create")
* @Method("POST")
*
*/
 public function createAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
  return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}

$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity, array(
    'action' => $this->generateUrl('demo_create'),
    'method' => 'POST',
));

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
  $data = $form->getData();
  return new JsonResponse(
          [
            'message' => 'Success!',
            'data' => $data 
          ], 200);
}

$response = new JsonResponse(
        array(
    'message' => 'Error',
    'form' => $this->renderView('default/new.html.twig', array(
        'entity' => $entity,
        'form' => $form->createView(),
    ))), 400);
return $response;
 }
}

和 JavaScript 代码:

  function initAjaxForm()
    {
    $('body').on('submit', '.ajaxForm', function (e) {

    e.preventDefault();

    $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize()
    })
    .done(function (data) {
        if (typeof data.message !== 'undefined') {
            console.log(data.data);
            console.log(data.message);
        }
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        if (typeof jqXHR.responseJSON !== 'undefined') {
            if (jqXHR.responseJSON.hasOwnProperty('form')) {
                $('#form_body').html(jqXHR.responseJSON.form);
            }

            $('.form_error').html(jqXHR.responseJSON.message);

        } else {
            alert(errorThrown);
        }

    });
});
}

最佳答案

今天在 2.8 版本中遇到了同样的问题,我将把它留在这里,以防它最终治愈其他人,我已将其添加到我的表单生成器中

/**
 * {@inheritdoc}
 */
public function getBlockPrefix()
{
    return '';
}

关于javascript - Symfony 表单 AJAX 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43136014/

相关文章:

javascript - 在 Google Chrome 中创建面板

java - 与 Symfony2 应用程序相比,spring MVC 表示层应该如何构建?

php - AJAX 是不是调用 PHP?

javascript - Jquery Ajax Json 对象

javascript - Ajax 请求似乎被调用了两次,但是其他 javascript 以及 Ajax 请求只被调用了一次

Javascript、php 和 html 编译器

javascript - 将 header 发送到 Node.JS 中的客户端后无法设置 header

javascript - 在 jQuery 中,你能得到正在褪色的元素的 "target"不透明度吗?

php - 读取初始通信数据包时与 MySQL 服务器失去连接,系统错误 : 111

PHP:Preg_match_all 将 html 提取到字符串中