Cha*_*eus 5 validation ajax asp.net-mvc jquery response
甚至不确定这是否是标题问题的正确方法.我知道我的AJAX调用都是错误的...这就是我现在正在做的事情(顺便说一句,我正在使用ASP.NET MVC后端):
我用来jQuery.ajax将一些数据发布到一个动作,这将加载我在响应中捕获的视图.它基本上为一个动作提供了一些数据,并取回了一些HTML.
假设我想创建一个经过验证的Ajax调用.如何在出错时收回验证消息?例如,Ajax登录表单.如果用户无法验证,我想告诉他们......而不是简单地无所事事.
抱歉天真的问题,我只是不知道如何在Google上找到解决方案.
先感谢您!
首先,如果您希望AJAX调用返回您计划在脚本中使用的数据(并且使用我的意思是更复杂,然后在a中显示该数据div),您应该从服务器返回JSON数据而不是HTML.JSON实际上是一个JS对象,所以它可以在收到它的时候用在JS中.
所以,如果你返回数据,即
{id: 1, status: 'ok'}
Run Code Online (Sandbox Code Playgroud)
你可以使用这样的东西来使用这些数据.
$.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');
}
}
Run Code Online (Sandbox Code Playgroud)
});
您需要为您的回复返回多条信息.幸运的是,您可以使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
这将转换为具有属性".Success",".Data"和".Errors"的javascript对象.
因此,如果您的验证代码填充了Errors数组并包含所有验证错误,那么您的ajax回调函数将很容易
确定调用的预期目的失败,因为SUCCESS属性设置为"失败".
获取所有相关的错误字符串.
您可以在动作方法中使用这种模式轻松完成此操作:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9403 次 |
| 最近记录: |