【发布时间】:2014-12-22 04:53:45
【问题描述】:
我的 Symfony2 控制器中有一个函数通过 Ajax 从视图中调用。这是控制器端的代码(不是真实的示例):
public function addFabAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$response['success'] = TRUE;
if ($request->isXmlHttpRequest()) {
$entity = new Entity();
$form = $this->createForm(new EntityForm(), $entity);
$form->handleRequest($request);
if ($form->isValid()) {
try {
$em->persist($entity);
$em->flush();
$response['entities'] = array();
$dataResponse = array();
$dataResponse['colOne'] = $$entity->getColumnOne();
$dataResponse['colTwo'] = $$entity->getColumnTwo();
$response['entities'][] = $dataResponse;
} catch (Exception $ex) {
$response['success'] = FALSE;
}
} else {
// Response for go through .fail() callback in Ajax request
}
return new JsonResponse($response);
}
}
然后在视图中我调用一些事件如下:
$.post(Routing.generate('addFab'), $form.serialize(), 'json').done(function (data, textStatus, jqXHR) {
// if all goes fine then show messages and much more
}
}).fail(function () {
// if something goes wrong then show and alert and try to show info to the user
return false;
}).always();
现在,如果$form->isValid() 为真,则始终会发出请求,因此将通过.done() 回调,因此我需要返回一些内容,不清楚是什么,如果表单无效,则响应通过.fail()回调,否则我总是需要检查,例如,$response['success'] 在 .done() 回调中是 TRUE 还是 FALSE,忘记了 .fail(),这对我来说似乎是错误的。如果正确的方法是使用 HttpFoundation Componente 或其他东西返回异常,我现在不知道,所以有什么建议吗?最好的方法是什么?
【问题讨论】:
-
检查错误
fail(function (jqXHR, status, error) { alert(status+':' + error) // if something goes wrong then show and alert and try to show info to the user return false; })的原因是什么 - 可能是响应格式不正确并且您遇到了解析错误 -
@ArunPJohny 也许我的问题一点都不好,我的意思是我需要从我的控制器响应任何失败,不仅仅是表单验证,而且其他示例可能是无效的表单凭据,重复字段DB和其他东西,你现在拿到了吗?
-
在这种情况下,您需要将响应状态设置为 400 或任何其他错误状态。可能类似于
<?php http_response_code(400); ?>
标签: javascript php jquery ajax symfony