[英]Can we process a form with Symfony2 without redirect to another url at the end?
I have problem with processing the data on a form in two tables with Ajax for not updating screen. 我在使用Ajax处理两个表中的表单上的数据时遇到问题,无法更新屏幕。 Sumfony2 redirects to process the data to a url in the end, as you can see in the following code:
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 call: 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;
});
Is there any way that does not forward it to any URL and can use Ajax to load anything in that window? 有没有办法不将其转发到任何URL,并且可以使用Ajax在该窗口中加载任何内容?
replace 更换
return $this->redirect($this->generateUrl('users_new'));
by 通过
return new JsonResponse($this->generateUrl('users_new'));
this will return the url instead of redirecting to it, you can then use javascript to load it. 这将返回网址,而不是重定向到该网址,然后您可以使用JavaScript加载该网址。
You can check on the $request if is an ajax call with the isXmlHttpRequest
method. 您可以使用
isXmlHttpRequest
方法检查$ request是否为ajax调用。
So you can do something like: 因此,您可以执行以下操作:
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'));
}
Hope this help 希望这个帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.