如何处理 jQuery AJAX 错误?
jqueryweb developmentfront end technology
要处理 jQuery AJAX 错误,可以使用 `ajaxError(callback)` 方法,该方法会附加一个函数,该函数会在 AJAX 请求失败时执行。这是一个 AJAX 事件。
以下是此方法使用的所有参数的说明
- callback要执行的函数。XMLHttpRequest 及其用于该请求的设置将作为参数传递给此函数。如果在处理请求时发生异常,则会传递第三个参数,即异常对象。
以下示例展示了此方法的用法:
<html>
<head>
<title>Handling errors in jQuery</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#driver").click(function(event){
/* Assume result.text does not exist. */
$('#stage1').load('/jquery/result.text');
});
$(document).ajaxError(function(event, request, settings ){
$("#stage2").html("<h1>Error in loading page.</h1>");
});
});
</script>
</head>
<body>
<p>Click on the button to load result.text file:</p>
<div id = "stage1" style = "background-color:blue;">
STAGE - 1
</div>
<div id = "stage2" style = "background-color:blue;">
STAGE - 2
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>

