5

甚至不确定这是否是为问题命名的正确方法。我知道我的 AJAX 调用都错了......这就是我现在正在做的事情(顺便说一下,我正在使用 ASP.NET MVC 后端):

我使用jQuery.ajax将一些数据发布到一个动作,这将加载我在响应中捕获的视图。它基本上是为动作提供一些数据,并取回一些 HTML。

假设我想创建一个经过验证的 Ajax 调用。我如何取回错误的验证消息?例如,一个 Ajax 登录表单。如果无法验证用户,我想告诉他们......而不是简单地什么都不做。

抱歉这个天真的问题,我只是不知道如何正确地在谷歌上找到解决方案。

先感谢您!

4

4 回答 4

7

首先,如果您希望 AJAX 调用返回您计划在脚本中使用的数据(并且使用我的意思是比在 a 中显示该数据更复杂div),您可能应该从服务器返回 JSON 数据而不是 HTML。JSON 实际上是一个 JS 对象,所以它在收到的那一刻就可以在 JS 中使用。

因此,如果您返回数据,即

{id: 1, status: 'ok'}

您可以使用类似的东西来使用该数据。

$.ajax({
    url: "your/script/url",
    type: "POST",
    data: {login : 'foo', pass: 'bar'}, // whatever the data is
    dataType: "json",
    success: function(data){
        if (data.status === 'ok') {
            console.log('success');
        } else {
            console.log('error');
        }
    }

});

于 2009-08-12T06:04:48.773 回答
5

您需要返回多条信息以供回复。幸运的是,你可以使用 JSON 轻松地做到这一点,如果你告诉它响应类型是 json,jQuery 会自动为你处理它。您进入 ajax 回调函数的对象将包含您需要的所有数据作为不同的属性。

我建议养成在每次 ajax 调用时返回“成功”或“失败”状态代码的习惯,以及一系列错误。 有关我的意思的更多信息,请参阅这篇很棒的博客文章。

原因是 ajax 调用从根本上总是“成功”,除非服务器实际上无法处理请求并返回失败的 http 状态代码。如果请求的结果类似于验证错误,但服务器仍然返回某种文本响应,那么即使应用程序操作失败,ajax 调用仍然被认为是成功的。

因此,如果在您的操作方法中,不是在操作结果中返回您的 html 数据,而是返回一个像这样的对象:

public class AjaxResponse
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AjaxResponse"/> class.
        /// This creates an AjaxResponse that by default indicates SUCCESS.
        /// </summary>
        public AjaxResponse()
        {
            Success = true;
            Data = new List<object>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AjaxResponse"/> class.
        /// This creates an AjaxResponse that indicates FAILURE.
        /// </summary>
        /// <param name="exception">The exception.</param>
        public AjaxResponse(Exception exception)
            : this()
        {
            Success = false;
            Errors = new [] { exception.Message };
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AjaxResponse"/> class.
        /// This creates an AjaxResponse that indicates SUCCESS.
        /// </summary>
        /// <param name="data">The data.</param>
        public AjaxResponse(object data)
            : this()
        {
            Data = data;
        }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="AjaxResponse"/> is success.
        /// </summary>
        /// <value><c>true</c> if success; otherwise, <c>false</c>.</value>
        public bool Success
        {
            get; set;
        }

        /// <summary>
        /// Gets or sets the data.
        /// </summary>
        /// <value>The data.</value>
        public object Data
        {
            get; set;
        }

        /// <summary>
        /// Gets or sets the errors.
        /// </summary>
        /// <value>The errors.</value>
        public string[] Errors
        {
            get; set;
        }
    }

这将转换为具有“.Success”、“.Data”和“.Errors”属性的javascript对象。

因此,如果您的验证代码已经使用所有验证错误填充了 Errors 数组,那么您的 ajax 回调函数将很容易

  1. 确定调用的预期目的失败,因为 SUCCESS 属性设置为“失败”。

  2. 获取所有相关的错误字符串。

您可以在您的操作方法中使用这种模式轻松地做到这一点:

    try
    {
        instance.Validate();
        return Json(new AjaxResponse(myHtmlData));
    }
    catch(Exception ex)
    {
        var response = new AjaxResponse(ex);

        // Get your validation errors here, put them into
        // your ajax response's Errors property.

        return Json(response);
    }
于 2009-08-12T06:08:19.063 回答
2

我在博客上写过同样的情况。也许它也会对您的情况有所帮助。它基本上是关于拥有一个自定义异常类和一个将返回错误的异常操作属性。因此,您可以使用调用的successerror选项$.ajax。在我看来,这是正确的做法。

$.ajaxcall 确实提供了处理成功和错误响应的功能。无需总是返回成功并设置您必须在客户端上检查的错误标志。

于 2010-11-19T14:28:53.513 回答
0

我不确定我是否完全理解你的意思。但是您的错误验证消息示例不会像以下那样工作:

  1. 用户单击某些按钮/链接导致操作
  2. 异步发送回服务器,传输用户 ID(您应该注意这里的安全性)
  3. 在服务器上完成必要的验证并发送回响应(在 XML、Json 中,直接将消息编码为 HTML)
  4. 回到客户端,您会在 JavaScript 代码中获得响应并将其适当地放置在页面上

希望有帮助。

于 2009-08-12T06:08:11.560 回答