【问题标题】:Can we process a form with Symfony2 without redirect to another url at the end?我们可以使用 Symfony2 处理表单而不在最后重定向到另一个 url 吗?
【发布时间】:2016-02-19 01:43:27
【问题描述】:

我在使用 Ajax 处理两个表中的表单上的数据时遇到问题,因为不更新屏幕。 Sumfony2 将数据处理到最后重定向到一个 url,如下代码所示:

public function createAction(Request $request)
 {
    $entity = new Users();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

       if ($form->isValid()) {

        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();


    return $this->redirect($this->generateUrl('users_new'));
     }

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

ajax 调用:

$('.form_student').submit(function(event) {
event.preventDefault();

$.ajax({
type: 'POST',
url: Routing.generate('student_create'),
data: $(this).serialize(),

success: function(response) {

 alert(response.result);

  },
 error: function (xhr, desc, err){

 alert("error");
}
})
return false;
});

有什么方法可以不将其转发到任何 URL 并且可以使用 Ajax 在该窗口中加载任何内容?

【问题讨论】:

    标签: php ajax symfony


    【解决方案1】:

    您可以使用 isXmlHttpRequest 方法检查 $request 是否是 ajax 调用。

    所以你可以这样做:

    use Symfony\Component\HttpFoundation\JsonResponse;
    ....
    if ($form->isValid()) {
    
        // do something
        if ($request->isXmlHttpRequest()) {
                // generate a response for tour client, as example:
                return new JsonResponse(array("result" => 1);
            }
    
        return $this->redirect($this->generateUrl('users_new'));
     }
    

    希望有帮助

    【讨论】:

    • 我还是不能使用ajax中响应的值,我用你的例子alert (data.result);检查返回值,但是它表明它是未定义的。 Ajax 中如何使用响应对象?你能告诉我如何在 symfony 表单中使用错误验证字段来返回对我可以在不刷新页面的情况下显示错误的响应吗?
    • 嗨 @Joseph 很难用标准响应来响应...我通常通过自定义方法结合自定义 js ajax 管理来做这些事情...
    • 嗨@Matteo,对不起,但我不明白,我想你指的是我问的第二件事吧?我添加上面的代码 ajax 调用以查看尝试使用 Paraque 的答案,我指出它是否正确。
    • 嗨@Joseph 我回复你的问题stackoverflow.com/questions/34066421/…
    • 我现在才看到,我想我会为我所看到的提供很大的帮助,但我仍然做错了,因为我无法在 ajax 中获取控制器响应的值。我正在测试警报(response.result);并告诉我它是未定义的,你知道我哪里错了吗?
    【解决方案2】:

    替换

    return $this->redirect($this->generateUrl('users_new'));
    

    通过

    return new JsonResponse($this->generateUrl('users_new'));
    

    这将返回 url 而不是重定向到它,然后您可以使用 javascript 加载它。

    【讨论】:

    • 首先感谢@AmineMatmati 的回复。请原谅我的无知,但我不知道如何在 javascript 中使用该响应。我的想法是,一旦表单数据存储在数据库中,它就会加载重定向控制器的 url,例如使用 jquery 加载函数
    猜你喜欢
    • 2015-07-31
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2016-10-23
    • 2021-04-05
    • 1970-01-01
    • 2015-02-24
    相关资源
    最近更新 更多