ASP.NET MVC中的jQuery AJAX响应

时间:2021-04-13 03:19:10

Not even sure if this is the right way to title the question. I know I'm making my AJAX calls all wrong... here's what I'm doing right now (I'm using ASP.NET MVC backend by the way):

甚至不确定这是否是标题问题的正确方法。我知道我的AJAX调用都是错误的...这就是我现在正在做的事情(我正在使用ASP.NET MVC后端):

I use jQuery.ajax to post some data to an action, which will load a view that I capture in the response. It's basically providing some data to an action, and taking some HTML back.

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

Let's say I wanted to create an Ajax call that is validated. How do I get back the validation messages on error? For example, an Ajax login form. If the user cannot be validated, I'd like to tell them that... instead of simply doing nothing.

假设我想创建一个经过验证的Ajax调用。如何在出错时返回验证消息?例如,Ajax登录表单。如果用户无法验证,我想告诉他们......而不是简单地无所事事。

Sorry for the naive question, I just don't know how to word it right to find the solutions on Google.

抱歉天真的问题,我只是不知道如何在Google上找到解决方案。

Thank you in advance!

先谢谢你!

4 个解决方案

#1


7  

First of all if you want AJAX call to return the data you are planning to use in your scripts (and by use I mean something more complicated then displaying that data in a div), you should probably return JSON data instead of HTML from your server. JSON is actually a JS object so it can be used in JS the moment it is received.

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

So if you return the data i.e.

所以,如果你返回数据,即

{id: 1, status: 'ok'}

You can use something like this to use that data.

你可以使用这样的东西来使用这些数据。

$.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');
        }
    }

});

});

#2


5  

You'll need to return multiple pieces of information for your response. Luckily, you can do that easily using JSON, and jQuery will automatically handle it for you if you tell it the response type is json. The object that you get into your ajax callback function will contain all the pieces of data you need as different properties.

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

I would suggest getting into the habit of returning a status code of "success" or "failure" with each ajax call, and a collection of errors with it. See this awesome blog post for more information on what I mean.

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

The reason for this is that an ajax call will always fundamentally "succeed", unless the server actually couldn't process the request and returned a failure http status code. If the result of the request is something like a validation error, but the server still returns some kind of text response, then the ajax call is still considered to have succeeded, even though the application operation failed.

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

So if, in your action method, instead of returning your html data in an action result, if you returned an object like this:

因此,如果在操作方法中,而不是在操作结果中返回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;
        }
    }

This will translate into a javascript object that has properties ".Success", ".Data" and ".Errors".

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

So if your validation code had populated the Errors array with all the validation errors, it would be easy for your ajax callback function to

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

  1. determine that the intended purpose of the call had failed, because the SUCCESS property was set to "failure".

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

  2. Get all the relevant error strings.

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

You could do this easily with this kind of pattern in your action methods:

您可以在动作方法中使用这种模式轻松完成此操作:

    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);
    }

#3


2  

I've blogged about this same situation. Maybe it will help you in your situation as well. It's basically about having a custom exception class and an exception action attribute that will return the error. So you're able to use the success and error options of the $.ajax call. Which is in my opinion the right way of doing it.

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

$.ajax call does provide functionality to handle success as well as error responses. No need to always return a success with an error flag set that you have to check on the client.

$ .ajax调用确实提供了处理成功和错误响应的功能。无需始终返回成功,并设置了必须在客户端上检查的错误标志。

#4


0  

I'm not sure whether I fully understood what you mean. But your example of a validation message on an error, wouldn't that work like the following:

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

  1. User clicks on some button/link whatever which causes an action
  2. 用户点击某些按钮/链接导致操作的任何内容
  3. An asynchronouse post is done back to the server, transmitting the user id (you should be aware of security here)
  4. 一个asynchronouse帖子回到服务器,传输用户ID(你应该知道这里的安全性)
  5. On the server the necessary validation is done and a response send back (in XML, Json, directly the message encoded as HTML)
  6. 在服务器上进行必要的验证并发回一个响应(在XML中,Json,直接编码为HTML的消息)
  7. Back on the client side you get your response in your JavaScript code and place it appropriately on the page
  8. 回到客户端,您可以在JavaScript代码中获得响应,并将其放在页面上

Hope that helps.

希望有所帮助。

#1


7  

First of all if you want AJAX call to return the data you are planning to use in your scripts (and by use I mean something more complicated then displaying that data in a div), you should probably return JSON data instead of HTML from your server. JSON is actually a JS object so it can be used in JS the moment it is received.

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

So if you return the data i.e.

所以,如果你返回数据,即

{id: 1, status: 'ok'}

You can use something like this to use that data.

你可以使用这样的东西来使用这些数据。

$.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');
        }
    }

});

});

#2


5  

You'll need to return multiple pieces of information for your response. Luckily, you can do that easily using JSON, and jQuery will automatically handle it for you if you tell it the response type is json. The object that you get into your ajax callback function will contain all the pieces of data you need as different properties.

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

I would suggest getting into the habit of returning a status code of "success" or "failure" with each ajax call, and a collection of errors with it. See this awesome blog post for more information on what I mean.

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

The reason for this is that an ajax call will always fundamentally "succeed", unless the server actually couldn't process the request and returned a failure http status code. If the result of the request is something like a validation error, but the server still returns some kind of text response, then the ajax call is still considered to have succeeded, even though the application operation failed.

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

So if, in your action method, instead of returning your html data in an action result, if you returned an object like this:

因此,如果在操作方法中,而不是在操作结果中返回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;
        }
    }

This will translate into a javascript object that has properties ".Success", ".Data" and ".Errors".

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

So if your validation code had populated the Errors array with all the validation errors, it would be easy for your ajax callback function to

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

  1. determine that the intended purpose of the call had failed, because the SUCCESS property was set to "failure".

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

  2. Get all the relevant error strings.

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

You could do this easily with this kind of pattern in your action methods:

您可以在动作方法中使用这种模式轻松完成此操作:

    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);
    }

#3


2  

I've blogged about this same situation. Maybe it will help you in your situation as well. It's basically about having a custom exception class and an exception action attribute that will return the error. So you're able to use the success and error options of the $.ajax call. Which is in my opinion the right way of doing it.

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

$.ajax call does provide functionality to handle success as well as error responses. No need to always return a success with an error flag set that you have to check on the client.

$ .ajax调用确实提供了处理成功和错误响应的功能。无需始终返回成功,并设置了必须在客户端上检查的错误标志。

#4


0  

I'm not sure whether I fully understood what you mean. But your example of a validation message on an error, wouldn't that work like the following:

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

  1. User clicks on some button/link whatever which causes an action
  2. 用户点击某些按钮/链接导致操作的任何内容
  3. An asynchronouse post is done back to the server, transmitting the user id (you should be aware of security here)
  4. 一个asynchronouse帖子回到服务器,传输用户ID(你应该知道这里的安全性)
  5. On the server the necessary validation is done and a response send back (in XML, Json, directly the message encoded as HTML)
  6. 在服务器上进行必要的验证并发回一个响应(在XML中,Json,直接编码为HTML的消息)
  7. Back on the client side you get your response in your JavaScript code and place it appropriately on the page
  8. 回到客户端,您可以在JavaScript代码中获得响应,并将其放在页面上

Hope that helps.

希望有所帮助。