【问题标题】:What should my function return for Ajax request go through .fail() callback?我的 Ajax 请求函数应该通过 .fail() 回调返回什么?
【发布时间】: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


【解决方案1】:

当服务器返回 4xx 或 5xx 之类的错误状态或返回数据的客户端解析错误或请求中止调用时,将调用错误处理程序。

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

<?php
http_response_code(400);
?>

【讨论】:

    【解决方案2】:

    我知道这已经得到解答,但我认为这不是最好的方法。

    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,您也没有响应,但显然可以在其他地方处理。

    【讨论】:

      【解决方案3】:

      如果我在这里遗漏了一些东西,我不会感到惊讶,因为我不使用 $.post,我确实使用了 $.ajax,我猜这几乎是一样的。如果我在这里,.fail 是服务器响应 IIS 错误并且不应用于表单验证的时候。这应该在您的应用程序逻辑中完成,这将使其可以在 .done 中进行处理。如果我需要返回没有详细信息的否定响应,那么我将返回“false”,否则返回一个填充的 json 结果。

      【讨论】:

      • 嗨,我使用了Form 示例,但我想将其应用于任何其他代码。现在我正在按照你说的做,但是这样我需要一直检查done函数,例如,如果代码在success键(我的方式)上返回truefalse,这是我不太喜欢的,但如果这是唯一的方法,那么我会按照你说的做,是的 $.post$.get$.ajax 的简写 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      相关资源
      最近更新 更多