Ajax的进阶学习(一)

   在Ajax课程中,我们了解了最基本的异步处理方式。本章,我们将了解一下Ajax的一些全局请求事件、跨域处理和其他一些问题。

   加载请求

   在Ajax异步发送请求时,遇到网速较慢的情况,就会出现请求时间较长的问题。而超过一定时间的请求,用户就会变得不再耐烦而关闭页面。而如果在请求期间能给用户一些提
示,比如:正在努力加载中...,那么相同的请求时间会让用户体验更加的好一些。

   jQuery提供了两个全局事件.ajaxStart()和.ajaxStop()。这两个全局事件,只要用户触发了Ajax,请求开始时(未完成其他请求)激活.ajaxStart(),请求结束时(所有请求都结束了)激活.ajaxStop()。

   Ajax进阶.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Ajax进阶</title>
    <script type="text/javascript" src="jquery-1.12.3.js"></script>
    <script type="text/javascript" src="demo.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
    <form>
        用户名:<input type="text" name="user" />
        邮 件:<input type="text" name="email" />
        <input type="radio" name="sex" value="男" /><input type="radio" name="sex" value="女" /><input type="button" value="提交" />
    </form>
    <span class="loading">正在加载中...</span>
    <div id="box">
        
    </div>
</body>
</html>

   style.css:

.loading {
    display: none;
    color: red;
    font-weight: bold; 
}

   tomcat服务器端存在一个user.php,如下:

<?php
    echo $_POST['user'].' - '.$_POST['email'];
?>

   然后现在加载一个找不到的url,诸如:http://dsafsefre/user.php

$("form input[type=button]").click(function() {
    $.ajax({
        type:"post",
        url:"http://dsafsefre/user.php",
        data:$("form").serialize(),
        success:function(response, status, xhr) {
            $("#box").html(response);
        }
    });
});

   请求加载提示的显示和隐藏(必须绑定在document元素上)

$(document).ajaxStart(function() {
    $(".loading").show();
}).ajaxStop(function() {
    $(".loading").hide();
});

   如果请求时间太长,可以设置超时

$("form input[type=button]").click(function() {
    $.ajax({
        type:"post",
        url:"http://dsafsefre/user.php",
        data:$("form").serialize(),
        success:function(response, status, xhr) {
            $("#box").html(response);
        },
        timeout:500 //如果请求时间太长,可以设置超时
    });
});

   如果某个ajax不想触发全局事件,可以设置取消

$("form input[type=button]").click(function() {
    $.ajax({
        type:"post",
        url:"http://dsafsefre/user.php",
        data:$("form").serialize(),
        success:function(response, status, xhr) {
            $("#box").html(response);
        },
        timeout:500, //如果请求时间太长,可以设置超时
        global:false
    });
});

   若global置为false,那么以下代码将不起作用:

$(document).ajaxStart(function() {
    $(".loading").show();
}).ajaxStop(function() {
    $(".loading").hide();
});

   错误处理

   Ajax异步提交时,不可能所有情况都是成功完成的,也有因为代码异步文件错误、网络错误导致提交失败的。这时,我们应该把错误报告出来,提醒用户重新提交或提示开发者
进行修补。

   在之前高层封装中是没有回调错误处理的,比如$.get()、$.post()和.load(),所以早期的方法通过全局.ajaxError()事件方法来返回错误信息,而在jQuery1.5之后,可以通过连缀处理使用局部.error()方法即可,而对于$.ajax()方法,不但可以用这两种方法,还有自己的属性方法error : function () {}。

   $.ajax()使用属性提示错误:

$("form input[type=button]").click(function() {
    $.ajax({
        type:"post",
        url:"user1.php",
        data:$("form").serialize(),
        success:function(response, status, xhr) {
            $("#box").html(response);
        },
        error:function(xhr, errorText, errorStatus) {
            alert("错误!"); //错误!
            alert(errorText+":"+errorStatus); //error:Not Found
            alert(xhr.status+":"+xhr.statusText); //404:Not Found
        }
    });
});

   $.post()使用连缀.error()方法提示错误,连缀方法将被.fail()取代

$("form input[type=button]").click(function() {   
    $.post("user1.php").error(function(xhr, errorText, errorType) {
        alert("错误!"); //错误!
        alert(errorText+":"+errorType); //error:Not Found
        alert(xhr.status+":"+xhr.statusText); //404:Not Found
    });    
});

   $.post()使用全局.ajaxError()事件提示错误

$("form input[type=button]").click(function() {   
    $.post("user1.php");     
});
$(document).ajaxError(function(event, xhr, settings, infoError) {
    //alert("错误!"); //错误!
    //alert(event.type); //ajaxError
    //alert(event.target); //[object HTMLDocument]
    //for(var i in event) { 
    //    document.write(i + "<br/>"); //打印事件对象的属性和方法
    //}

    //alert(settings); //[object Object]
    //for(var i in settings) {
    //   document.write(i + "<br/>");
    //}
    //alert(settings.url); //user1.php
    //alert(settings.type); //post
    alert(infoError); //Not Found
});

   请求全局事件

   jQuery对于Ajax操作提供了很多全局事件方法,.ajaxStart()、.ajaxStop()、.ajaxError()等事件方法。他们都属于请求时触发的全局事件,除了这些,还有一些其他全局事件:

   .ajaxSuccess(),对应一个局部方法:.success(),请求成功完成时执行。

   .ajaxComplete(),对应一个局部方法:.complete(),请求完成后注册一个回调函数。

   .ajaxSend(),没有对应的局部方法,只有属性beforeSend,请求发送之前要绑定的函数。

   先看看.ajaxSend()/.ajaxSuccess()/.ajaxError()/.ajaxComplete()的执行顺序:

   以上代码除jQuery代码变化之外,其余均不变,jQuery代码如下:

$("form input[type=button]").click(function() {   
    $.post("user1.php");  //或$.post("user.php")   
});
$(document).ajaxSend(function() {
    alert("发送请求之前执行");
}).ajaxComplete(function() {
    alert("请求完成后,不管是否失败成功都执行");
}).ajaxSuccess(function() {
    alert("请求成功后执行");
}).ajaxError(function() {
    alert("请求失败后执行");
});

   注意:全局事件方法是所有Ajax请求都会触发到,并且只能绑定在document上,而局部方法,则针对某个Ajax。对于一些全局事件方法的参数,大部分为对象,而这些对象有哪些属性或方法能调用,可以通过遍历方法得到。

   $.post()使用局部方法.success()、.complete()、.error()、beforeSend是局部属性,没有对应的局部方法beforeSend()。

$("form input[type=button]").click(function() {        
    $.post("user1.php", $("form").serialize()).success(function() {
        alert("请求成功后执行");
    }).complete(function() {
        alert("请求完成后,不管是否失败成功都执行");
    }).error(function() {
        alert("请求失败后执行");
    }).beforeSend(function() {
        alert("发送请求之前执行"); //无效
    });
});

   $.ajax()方法,可以直接通过属性设置即可

$("form input[type=button]").click(function() {        
    $.ajax({
        type:"post",
        url:"user.php",
        data:$("form").serialize(),
        success:function(response, status, xhr) {
            alert("请求成功后执行");
        },
        complete:function() {
            alert("请求完成后,不管是否失败成功都执行");
        },
        beforeSend:function() {
            alert("发送请求之前执行");
        },
        error:function() {
            alert("请求失败后执行");
        }
    });
});

   注意:在jQuery1.5版本以后,使用.success()、.error()和.complete()连缀的方法,可以用.done()、.fail()和.always()取代。

  

原文地址:https://www.cnblogs.com/yerenyuan/p/5436025.html