离开页面时JQuery的阿贾克斯错误 [英] JQuery Ajax error when leaving page

查看:115
本文介绍了离开页面时JQuery的阿贾克斯错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code异步从服务器到客户端中提取数据。在错误块的警示报告在服务器上发生的错误。但是,如果用户从导航页页呼叫中旬了,这个模块也被炒鱿鱼,​​并抛出一个空容器警告。有什么办法来处理用户离开页面更优雅(他们离开之前,即,不是抛出一个空的警告)?也许通过区分在用户已经导航远的差错块,而不是发生在服务器上的错误?

  $。阿贾克斯({
    键入:GET,
    网址:/handlers/myHandler.ashx
    异步:真实,
    数据类型:JSON
    数据:VAR1 =为test_val&安培; VAR2 =为test_val
    成功:函数(发票){
       //块成功
    },
    错误:功能(XMLHtt prequest,textStatus,errorThrown){
        警报(errorThrown);
    }
});


解决方案

问题解决了..

我给自己定一个全局变量:

  VAR unloadingState = FALSE;

然后, beforeunload 事件句柄(感谢戴夫!),修改的变量:

  $(窗口).bind(beforeunload功能(){
    unloadingState = TRUE;
});

终于在AJAX方法的误差块的交叉引用:

 错误:功能(XMLHtt prequest,textStatus,errorThrown){
    警报(errorThrown);
}

是的警报是丑陋的,不应该被使用!

I am using the following code to asynchronously pull data from the server into the client. The alert in the error block reports errors that occur on the server. However if the user navigates away from the page page mid-call, this block also gets fired and throws an empty alert container. Is there any way to handle the the user leaving the page more gracefully (i.e. not throw an empty alert before they leave)? Maybe by differentiating in the error block that the user has navigated away, rather than an error occurring on the server?

$.ajax({
    type: "GET",
    url: "/handlers/myHandler.ashx",
    async: true,
    dataType: "json",
    data: "var1=test_val&var2=test_val"
    success: function (invoices) {
       //Success block
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

解决方案

Problem solved..

I've set a global variable:

var unloadingState = false;

Then a beforeunload event handle (thanks Dave!), to modify the variable:

$(window).bind("beforeunload", function () {
    unloadingState = true;
});

And finally a cross-reference in the error block of the ajax method:

error: function (XMLHttpRequest, textStatus, errorThrown) {
    alert(errorThrown);
}

And yes alerts are ugly and shouldn't be used!

这篇关于离开页面时JQuery的阿贾克斯错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆