前言
1.加载请求
2.错误处理
3.请求全局事件
在 Ajax 课程中,我们了解了最基本的异步处理方式。本章,我们将了解一下 Ajax 的 一些全局请求事件、跨域处理和其他一些问题。
一.加载请求
在 Ajax 异步发送请求时,遇到网速较慢的情况,就会出现请求时间较长的问题。而超 过一定时间的请求,用户就会变得不再耐烦而关闭页面。而如果在请求期间能给用户一些提 示,比如:正在努力加载中…,那么相同的请求时间会让用户体验更加的好一些。
jQuery 提供了两个全局事件,.ajaxStart()和.ajaxStop()。这两个全局事件,只要用户触发 了 Ajax,请求开始时(未完成其他请求)激活.ajaxStart(),请求结束时(所有请求都结束了) 激活.ajaxStop()。
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
注意:以上代码在 jQuery1.8 及以后的版本不在有效,需要使用 jquery-migrate 向下兼容 才能运行。新版本中,必须绑定在 document 元素上。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
二.错误处理
Ajax 异步提交时,不可能所有情况都是成功完成的,也有因为代码异步文件错误、网 络错误导致提交失败的。这时,我们应该把错误报告出来,提醒用户重新提交或提示开发者 进行修补。
在之前高层封装中是没有回调错误处理的,比如
.get()、
.post()和.load()。所以,早期 的方法通过全局.ajaxError()事件方法来返回错误信息。而在 jQuery1.5 之后,可以通过连缀 处理使用局部.error()方法即可。而对于$.ajax()方法,不但可以用这两种方法,还有自己的属 性方法 error : function () {}。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
三.请求全局事件
jQuery 对于 Ajax 操作提供了很多全局事件方法,.ajaxStart()、.ajaxStop()、.ajaxError() 等事件方法。他们都属于请求时触发的全局事件,除了这些,还有一些其他全局事件:
.ajaxSuccess(),对应一个局部方法:.success(),请求成功完成时执行。 .ajaxComplete(),对应一个局部方法:.complete(),请求完成后注册一个回调函数。
.ajaxSend(),没有对应的局部方法,只有属性 beforeSend,请求发送之前要绑定的函数。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
注意:全局事件方法是所有 Ajax 请求都会触发到,并且只能绑定在 document 上。而局 部方法,则针对某个 Ajax。
对于一些全局事件方法的参数,大部分为对象,而这些对象有哪些属性或方法能调用,可以通过遍历方法得到。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
注意:在 jQuery1.5 版本以后,使用.success()、.error()和.complete()连缀的方法,可以 用.done()、.fail()和.always()取代。