ASP.NET MVC 中的 jQuery AJAX 响应
-
13-09-2019 - |
题
甚至不确定这是否是标题问题的正确方式。我知道我的 AJAX 调用都是错误的......这就是我现在正在做的事情(顺便说一句,我正在使用 ASP.NET MVC 后端):
我用 jQuery.ajax
将一些数据发布到操作,该操作将加载我在响应中捕获的视图。它基本上是向操作提供一些数据,并取回一些 HTML。
假设我想创建一个经过验证的 Ajax 调用。出现错误时如何取回验证消息?例如,Ajax 登录表单。如果无法验证用户,我想告诉他们......而不是简单地什么都不做。
抱歉问了这个天真的问题,我只是不知道如何正确措辞才能在谷歌上找到解决方案。
先感谢您!
解决方案
所有的,如果你想AJAX调用返回您计划在您的脚本中使用(并利用我的意思是更复杂的东西,然后显示在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');
}
}
});
其他提示
您需要返回多条信息才能做出响应。幸运的是,您可以使用 JSON 轻松做到这一点,如果您告诉 jQuery 响应类型是 json,它会自动为您处理。您进入 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 回调函数将很容易
确定调用的预期目的失败,因为 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);
}
$.ajax
呼叫确实提供的功能来处理成功以及错误响应。没有必要总是返回成功与你必须检查客户端上的错误标志设置。
我不确定我是否完全理解你的意思。但是您的错误验证消息示例不会像下面这样工作:
- 用户单击某个按钮/链接,无论什么都会导致操作
- 异步发送回服务器,传输用户 ID(您应该注意这里的安全性)
- 在服务器上完成必要的验证并发回响应(在 XML、Json 中,直接将消息编码为 HTML)
- 回到客户端,您可以在 JavaScript 代码中获取响应并将其适当地放置在页面上
希望有帮助。