我正在使用 Symfony2 并执行 Ajax 调用来处理表单。我遇到的问题是,通过使用返回给我的 JsonResponse,驱动程序告诉我该值未定义。我想知道我在解决这个问题时做错了什么,并且是否可以以某种方式将错误返回到表单字段以从 Ajax 进行验证可以在表单中显示失败而无需刷新页面。
Controller :
public function createAction(Request $request){
$entity = new Student();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return new JsonResponse(array('message' => 'Success!'), 200);
}
return $this->render('BackendBundle:Student: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.message);
},
error: function (xhr, desc, err){
alert("error");
}
})
return false;
});
最佳答案
您需要以不同于常规 HTML 请求的方式处理 XMLHttpRequest。
目前,当发出 XMLHttpRequest 但表单失败时,整个页面会再次呈现(带有“成功”状态代码),但您只想返回带有消息和“失败”状态代码的响应。
以下内容应该对您有帮助。
public function createAction(Request $request)
{
// if request is XmlHttpRequest (AJAX) but not a POSt, throw an exception
if ($request->isXmlHttpRequest() && !$request->isMethod(Request::METHOD_POST)) {
throw new HttpException('XMLHttpRequests/AJAX calls must be POSTed');
}
$entity = new Student();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
// if the form was successful and the call was an AJAX request
// respond with a JSON Response (with a 201/created status code)
if ($request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'Success!'), 201);
}
// If the form was successful and the call was HTTP
// redirect to "show student"
return $this->redirect('student_show', array('id' => $entity->getId()));
}
// if request was an AJAX call and (obviously) the form was not valid
// return message about form failure
// (with a 400/Bad Request status code)
if ($request->isMethod(Request::METHOD_POST)) {
return new JsonResponse(array('message' => 'failed due to form errors'), 400);
// you could also loop through the form errors to create an array, use a custom
// form -> errors array transformer or use the @fos_rest.view_handler to output
// your form errors
}
return $this->render('BackendBundle:Student:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
已更新
JavaScript 应该像这样工作。
$('.form_student').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: Routing.generate('student_create'),
data: $(this).serialize(),
dataType: 'json',
// if "student_create" returns a 2** status code
success: function(response) {
// should return "Success!"
alert(response.message);
},
// if "student_create" returns a non-2** status code
error: function (xhr, desc, err){
// if the response was parsed to json and has a message key
if (xhr.responseJSON && xhr.responseJSON.message) {
alert(xhr.responseJSON.message);
// otherwise use the status text
} else {
alert(desc);
}
}
});
return false;
});
关于javascript - 如何将 JsonResponse 与 ajax 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34068949/