如何将JsonResponse与ajax结合使用
How to use a JsonResponse with ajax
我正在使用Symfony2并执行Ajax调用来处理表单。我遇到的问题是,通过使用返回给我的JsonResponse
,驱动程序告诉我该值未定义。我想知道我在解决这个问题时做错了什么,以及是否可以以某种方式将错误返回到表单字段以从Ajax进行验证。Ajax可以在不刷新页面的情况下显示表单中的失败。
控制器:
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;
});
使用ajax,返回将不起作用
return new JsonResponse(array('message' => 'Success!'), 200);
您应该使用PHP echo
打印该值,以便在ajax成功回调中使用它,例如
echo new JsonResponse(array('message' => 'Success!'), 200);
您需要两个操作:
1.动作秀
显示操作应该处理您的表单接口。例如:
public function showAction(Request $request){
$entity = new Student();
$form = $this->createCreateForm($entity);
return $this->render('BackendBundle:Student:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
2.动作手柄保存
操作保存应处理ajax请求保存数据的情况。例如:
public function createAction(Request $request)
{
//get all data post
$data = $request->request->all();
extract($data, EXTR_PREFIX_SAME, "wddx");
// if you want to see the result uncoment below
// dump($data); // uncomment this to see data
//$id = $data['id'];
//$name = $data['name'];
$student = new Student();
//$student->.... = ... // set your field
//...
//...
try {
// try save entity
$em = $this->getDoctrine()->getManager();
$em->persist($student);
$em->flush();
} catch ('Exception $e) {
// set your error message ...
}
}
注意:
记住更改url: Routing.generate('student_create')
点以保存句柄
相关文章:
- 将图像上传ajax与表单提交ajax相结合
- 如何将 AJAX 与 JSON 结合使用
- 将post方法与php、ajax和javascript结合使用
- Ajax成功地将表与progressbar结合起来
- ajax和tweenmax的结合
- AJAX:结合上传文件和文本输入代码
- Ajax 将关联数组与表单序列化相结合
- 如何将简单的 JQuery 自动完成语法与对远程数据源(PHP 脚本)的 ajax 调用相结合
- 将多个引导按钮与 jquery Ajax 结合使用
- 结合两个javascript函数来验证表单并通过ajax提交
- 将 IBM watson API 与 jquery 的 $.ajax 结合使用
- Jquery getScript 或 ajax 与 php flush 相结合
- 将Ajax与JSF命令按钮或表单结合使用
- $.ajax与$.ajaxSetup默认设置相结合
- 如何将JsonResponse与ajax结合使用
- 将Ajax与表排序/筛选相结合
- PHP/AJAX -建议替换iFrame与DIV(结合AJAX)
- ajax/PHP (Icecast) -如何结合ajax和PHP
- 关于结合ajax,php和javascript
- 结合AJAX请求来加载带有变量的新页面