我的函数应该通过.fail()回调为Ajax请求返回什么


What should my function return for Ajax request go through .fail() callback?

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()为TRUE或否,则总是发出请求,因此将通过.done()回调,所以我需要返回一些东西,不清楚是什么,如果表单无效,则响应通过.fail()回调,否则我总是需要检查.done()回调中的$response['success']是TRUE还是FALSE,而忘记.fail(),这对我来说似乎是错误的。我现在不知道是否正确的方法是使用HttpFoundation组件或其他东西返回异常,有什么建议吗?最好的方法是什么?

当服务器返回错误状态(如4xx或5xx)时,或者当客户端对返回的数据进行解析错误时,或者在请求上进行中止调用时,会调用错误处理程序。

在这种情况下,由于基于验证,您希望将请求发送到故障处理程序,因此需要将响应状态设置为类似400的错误状态。所以在你的else区块中尝试

<?php
http_response_code(400);
?>

我知道这个问题已经得到了答案,但我认为这不是最好的方法。

JsonResponse对象将状态代码作为第二个参数,因此与其在代码中粘贴http_response_code,不如将状态代码添加到其中。

此外,与其将success默认为true,不如将其默认为false,然后成功更新它。

你可以这样做。。

public function addFabAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $response['success'] = false;
    $status = null;
    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;
                $response['success'] = true;
            } catch (Exception $ex) {
                $status = 400; // Your error code
                $response['error_message'] = 'something';
            }
        } else {
            $status = 400;
            $response['error_message'] = 'form not valid';
        }
        return new JsonResponse($response, $status ?: 200);
    }
}

此外,如果请求不是XmlHttpRequest,则您没有响应,但显然可以在其他地方处理。

如果我在这里遗漏了什么,我不会感到惊讶,因为我不使用$.post,我确实使用了$.ajax,我想这几乎是一样的。如果我在这里,.fail是指服务器响应IIS错误,不应用于表单验证。这应该在你的应用程序逻辑中完成,这样就可以在.done中正确处理。如果我需要返回一个没有详细信息的否定响应,那么我会返回"false",否则会返回一个填充的json结果。