【问题标题】:How to get jquery ajax error data, and is it the correct way to respond?如何获取jquery ajax错误数据,是正确的响应方式吗?
【发布时间】:2017-05-09 23:50:25
【问题描述】:

我正在使用 ajax 提交表单。 这是我写的一段代码:

    $.post(this.action, $(this).serialize())
        .done(function(data) {
            form.find(".success-msg").text(data);
        })
        .fail(function() {
            // insert error msg to the form
        })
        .always(function() {
             modal.modal("hide");
        });

如何在失败处理程序中获取服务器响应? .fail() 回调没有像 .done() 那样得到返回的数据。

其次,对于服务器上发生的表单验证错误返回非 200(比如 40X)状态是否正确?或者我应该返回 200 OK 状态并以某种方式在我自己的响应中区分错误/成功?

即验证错误我可以这样做

return HttpResponse(error_msg)

或者,

return HttpResponseBadRequest(error_msg)

【问题讨论】:

    标签: jquery ajax django forms django-forms


    【解决方案1】:

    这可能会晚,但我最近遇到了同样的问题,这是我的解决方案。

        .error(function(xhr){
           var result = xhr.responseJSON;
           form.find(".error-message").text(result.data);
         });
    

    您始终可以通过控制台记录 xhr.responseJSON 以确定返回的内容。

    【讨论】:

      【解决方案2】:

      done 部分你有:

      .done(function(data) {
          form.find(".success-msg").text(data);
      });
      

      但在 fail 中,您没有包含 data 参数。如果你想使用它,你应该包含它:

      .fail(function(data) {
          // insert error msg to the form
      });
      

      关于另一个问题 - 如果您知道失败的原因 - 我认为最好使用 200 回复并在回复中包含 status: true/false 和其余数据。这样,如果您遇到其他错误代码(服务器未响应/服务器错误/等),您可以使用不同的功能/行为。

      【讨论】:

        猜你喜欢
        • 2012-02-22
        • 2019-07-13
        • 2010-12-10
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 2018-05-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多