我在 Firefox 中遇到了一个问题(在 IE 中不会发生),我的 Javascript 启动了对服务的调用,这可能需要一些时间来加载。如果用户在调用完成之前导航到另一个页面,则会调用 jQuery.ajax()
对象的 error
方法。
我正在寻找一种方法:
- 当请求未完成时用户浏览到另一个页面时不会引发错误,或者
- 让错误方法区分“真实”错误和此错误。
毫不奇怪,我的错误方法会向用户显示错误,而当错误是由于导航到另一个页面而引起时,我不想这样做。
我的简单测试代码涉及以下 JavaScript 和一个休眠 20 秒然后返回字符串的服务。
<script type="text/javascript" language="javascript">
$(document).ready(function ()
{
$('#testLink').click(function ()
{
$.ajax({
type: "POST",
url: "/Services/NU.Web.NUnet.Services.UserService.asmx/LongRunningService",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, xhr)
{
console.log(data);
console.log(textStatus);
console.log(xhr);
},
error: function (xhr, textStatus, errorThrown)
{
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
}
});
});
});
</script>
最佳答案
尝试:
<script type="text/javascript" language="javascript">
$(function() {
$('#testLink').click(function() {
$.ajax({
type: "POST",
url: "/Services/NU.Web.NUnet.Services.UserService.asmx/LongRunningService",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, xhr){
console.log(data);
console.log(textStatus);
console.log(xhr);
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status === 500) {
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
}
}
});
});
});
</script>
关于jquery - 在请求完成之前浏览到另一个页面时 $.ajax 调用会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2868666/