在 jQuery 中处理 $.ajax 失败
今天的文章将讨论在 jQuery 中处理 AJAX 中的失败请求。
处理 jQuery 中的 $.ajax
失败
jQuery 的 AJAX 发布请求执行异步 HTTP (AJAX) 请求。
语法:
jQuery.ajax([settings]).fail((jqXHR, textStatus) => {});
jQuery.ajax(url[, settings]).fail((jqXHR, textStatus) => {});
其中,
.fail()
方法取代了已弃用的 .error()
方法。这是错误回调选项的替代构造。
如果请求失败,则在 AJAX
配置中调用 error
回调选项。它接收 jqXHR
、指示错误类型的字符串和异常对象(如果有)。
一些内置错误将字符串作为异常对象返回,例如:abort
、timeout
、no transport
。
$.ajax()
返回 jQuery XMLHttpRequest
(jqXHR
) 对象,它是浏览器原生 XMLHttpRequest
对象的超集。
让我们通过以下示例来理解它。
HTML 代码:
<form id="myForm">
<label for="name">Name</label>
<input id="name" name="name" type="text" value="Smith" />
<input type="submit" value="Send" />
</form>
JavaScript 代码:
$('#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
method: 'POST',
url: '/open/hello-world',
data: {name: 'Smith', location: 'United State'},
error: function(jqXHR, thrownError) {
alert(jqXHR.status);
alert(thrownError);
}
})
.done(function(msg) {
alert('Data Saved: ' + msg);
})
.fail((jqXHR, errorMsg) => {alert(jqXHR.responseText, errorMsg)});
})
在上面的示例中,一旦用户提交了表单,就会使用指定的 URL 和参数向服务器发送 AJAX 调用。当服务器返回成功消息时,你可以在控制台上打印该消息或使用适当的消息通知用户。
如果服务器返回错误消息,你可以使用错误处理程序或 .fail()
捕获错误,并使用适当的错误消息通知用户。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。