Php 我们是否可以使用Symfony2处理表单,而不在最后重定向到另一个url?
为了不更新屏幕,我在使用Ajax处理两个表中表单上的数据时遇到了问题。Sumfony2重定向,最终将数据处理到url,如以下代码所示:Php 我们是否可以使用Symfony2处理表单,而不在最后重定向到另一个url?,php,ajax,symfony,Php,Ajax,Symfony,为了不更新屏幕,我在使用Ajax处理两个表中表单上的数据时遇到了问题。Sumfony2重定向,最终将数据处理到url,如以下代码所示: public function createAction(Request $request) { $entity = new Users(); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form
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加载该窗口中的任何内容?替换
return $this->redirect($this->generateUrl('users_new'));
借
这将返回url而不是重定向到它,然后您可以使用javascript加载它。如果$request是一个ajax调用,您可以使用
isXmlHttpRequest
方法检查$request
因此,您可以执行以下操作:
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'));
}
希望这些帮助首先感谢@AmineMatmati的回复。请原谅我的无知,但我不知道如何在javascript中使用该响应。我的想法是,一旦表单数据存储在数据库中,它就会加载重定向控制器的url,例如使用jquery加载函数我仍然无法在ajax中使用响应值,我使用了您的示例
alert(data.result)
检查返回值,但它表示返回值未定义。Ajax中如何使用响应对象?您还可以告诉我如何使用symfony表单中的错误验证字段将响应返回到我可以在不刷新页面的情况下显示错误吗?Hi@Joseph很难使用标准响应进行响应。。。我通常是通过一种定制的方法结合一种定制的js ajax管理来做这些事情的……嗨@Matteo,对不起,我不明白,我想你是指我问的第二件事吧?。我添加了上面的代码ajax调用,以查看是否尝试使用Paraque answer me来指示它是否正确。您好@Joseph我回答了刚才看到的您的问题,我想我会为我所看到的提供很大帮助,但我仍然在做一些错误的事情,因为我无法在ajax中获得控制器响应的值。我正在测试一个警报(response.result);告诉我它是未定义的,你知道我可能错在哪里吗?
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'));
}