在请求完成之前浏览到另一个页面时,$ .ajax调用抛出错误

时间:2010-05-19 19:20:33

标签: jquery ajax

我在Firefox中遇到了一个问题(在IE中没有发生),我的Javascript开始调用服务,这可能需要一点时间来加载。如果用户在调用完成之前导航到另一个页面,则会调用error对象的jQuery.ajax()方法。

我正在寻找一种方法:

  1. 当请求未完成时用户浏览另一个页面时没有抛出错误,或者
  2. 让错误方法区分“真实”错误和此错误。
  3. 我的错误方法毫不奇怪地向用户显示错误,并且当导航到另一个页面导致错误时我不想这样做。

    我的简单测试代码涉及以下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> 
    

1 个答案:

答案 0 :(得分:3)

尝试:

<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>