Javascript 如何在ajax中使用JsonResponse
我正在使用Symfony2并执行Ajax调用来处理表单。我的问题是,通过使用返回我的Javascript 如何在ajax中使用JsonResponse,javascript,php,jquery,ajax,symfony,Javascript,Php,Jquery,Ajax,Symfony,我正在使用Symfony2并执行Ajax调用来处理表单。我的问题是,通过使用返回我的JsonResponse,驱动程序告诉我该值未定义。我想知道我在解决这个问题时做错了什么,还想知道是否可以通过某种方式将错误返回到表单字段,以便通过Ajax进行验证,从而在不刷新页面的情况下显示表单中的失败 控制器: public function createAction(Request $request){ $entity = new Student(); $form = $this->createC
JsonResponse
,驱动程序告诉我该值未定义。我想知道我在解决这个问题时做错了什么,还想知道是否可以通过某种方式将错误返回到表单字段,以便通过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;
});
使用ajax时,return将不起作用
return new JsonResponse(array('message' => 'Success!'), 200);
您应该使用PHPecho
打印该值,以便在ajax成功回调中使用它,例如
echo new JsonResponse(array('message' => 'Success!'), 200);
您需要以不同于常规HTML请求的方式处理XMLHttpRequests 目前,当发出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;
});
您需要有两个操作: 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')
指向保存句柄这个答案很好,所以我不会再做新的。但是如果您使用回调done
来获取响应hi@sidneylebrand,我仍然认为该值未定义。@Thomas,success()
也会这样做。@NiranjanNRaju几乎相同,success
仅当返回的请求的http状态为200
时才会激发,否则将调用fail
,在每个请求结束时调用done
,而不管请求是否失败或成功。这是不正确的。该操作需要返回响应,而不是回显JSONResponse。回显它只是意味着它将响应(状态代码、标题和内容)打印为字符串,然后继续返回后一个响应。是否尝试调试它?尝试执行echo json_encode(['message'=>'success']);退出createAction方法第一行中的
。你好@Robert,请原谅我的无知,因为我是新手,我将echo json_encode(['message'=>'success']
在createAction方法的第一行,给了我一个错误。这是你的意思吗?不,他的意思是更改返回新的JsonResponse(数组('message'=>'Success!'),200);
到回显新的JsonResponse(数组('message'=>'Success!'),200);退出;
。然后它是否正确你的urlurl:Routing.generate('student\u create'))
?您好@hendrathings,我尝试了您所说的,但未定义的值仍然存在,AJAX调用成功执行,但不知道,因为没有获得响应的值。URL是正确的。您好@Qoopmao,首先感谢您的回答。我理解您向我指出的一切,但我必须使用AJAX响应,因为e我没有得到正确的信息。你能给我添加一个ajax代码和一个例子来看看我可能失败的地方吗?我已经对你的代码进行了注释。这更有意义吗?嗨@Qoopmao,我一直在尝试更改你之前告诉我的内容,我得到了第一个METHOD\u POST错误,表明它没有定义。错误:未定义的类常量'METHOD\u POST'在/opt/lampp/htdocs/Symfony/src/BackendBundle/Controller/StudentController.php第40行删除这段代码时,我设法得到了400个错误,错误消息(我在控制台上看到)与他现在向我指示的方式相同。是$request->isMethod(request::METHOD_POST)还是$request->isMethod('POST')?我更改了它,但现在总是显示错误消息,尽管您在表单中输入了正确的值,但从来没有成功执行过ajax调用。是的,Request::METHOD_POST
只使用常量,但它仅在2.6+版本中可用,因此您可能不需要根据您的版本进行调用。我真的不知道剩下的内容是什么你的问题的意思是抱歉。