jQuery基础---Ajax进阶

内容提纲:

1.加载请求

2.错误处理

3.请求全局事件

4.JSON 和 JSONP

5.jqXHR 对象

发文不易,转载请注明出处!

 

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

一.加载请求

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

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

//请求加载提示的显示和隐藏

$('.loading').ajaxStart(function () {

  $(this).show();

  }).ajaxStop(function () {

  $(this).hide();

});

PS:以上代码在 jQuery1.8 及以后的版本不再有效,需要引入jquery-migrate 向下兼容文件才能运行。新版本中,必须绑定在 document 元素上

$(document).ajaxStart(function () {

  $('.loading').show();

  }).ajaxStop(function () {

  $('.loading').hide();

});

 

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

$.ajax({

  timeout : 500

});

 

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

$.ajax({

  global : false

});

 

二.错误处理

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

 

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

//$.ajax()使用属性方法提示错误

 1 $.ajax({
 2 
 3     type : 'POST',
 4 
 5     url : 'test1.php',
 6 
 7     data : $('form').serialize(),
 8     
 9     success : function (response, status, xhr) {
10 
11         $('#box').html(response);
12 
13     },
14 
15     error : function (xhr, errorText, errorStatus) {
16 
17         alert(xhr.status + ':' + xhr.statusText);
18 
19     }
20 
21 });

 

 

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

$.post('test1.php').error(function (xhr, status, info) {   //参数和上面一样

  alert(xhr.status + ':' +xhr.statusText);

  alert(status + ':' + info);

});

 

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

$(document).ajaxError(function (event, xhr, settings, info) {   //event为事件对象

  alert(xhr.status + ':' +xhr.statusText);

  alert(settings+ ':' + info);

});

 

三.请求全局事件

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

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

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

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

 

//$.post()使用局部方法.success()

1 $.post('test.php', $('form').serialize(), function (response, status, xhr) {
2 
3     $('#box').html(response);
4 
5     }).success(function (response, status, xhr) {
6 
7     alert(response);
8 
9 });

 

//$.post()使用全局事件方法.ajaxSuccess()

$(document).ajaxSuccess(function (event, xhr, settings) {

  alert(xhr.responseText);

});

PS:全局事件方法是所有 Ajax 请求都会触发到,并且只能绑定在 document 上。而局部方法,则针对某个 Ajax。

 

对于一些全局事件方法的参数,大部分为对象,而这些对象有哪些属性或方法能调用,可以通过遍历方法得到。

//遍历 settings 对象的属性

$(document).ajaxSuccess(function (event, xhr, settings) {

  for (var i in settings) {

    alert(i);

  }

});

 

//$.post()请求完成的局部方法.complete()

$.post('test.php', $('form').serialize(), function (response, status, xhr) {

  alert('成功');

}).complete(function (xhr,status) {

  alert('完成');

});

//$.post()请求完成的全局方法.ajaxComplete()

$(document).ajaxComplete(function (event, xhr, settings) {

  alert('完成');

});

//$.post()请求发送之前的全局方法.ajaxSend()

$(document).ajaxSend(function (event, xhr, settings) {

  alert('发送请求之前');

});

 

//$.ajax()方法(参加ajax基础篇中此方法的参数),可以直接通过属性设置即可。

 1 $.ajax({
 2 
 3     type : 'POST',
 4 
 5     url : 'test.php',
 6 
 7     data : $('form').serialize(),
 8 
 9     success : function (response, status, xhr) {
10 
11         $('#box').html(response);
12 
13     },
14 
15     complete : function (xhr, status) {
16 
17         alert('完成' + ' - ' + xhr.responseText + ' - ' + status);
18 
19    } ,
20 
21     beforeSend : function (xhr, settings) {
22 
23         alert('请求之前' + ' - ' + xhr.readyState + ' - ' + settings.url);
24 
25     }
26 
27 });

 

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

 

四.JSON 和 JSONP

如果在同一个域下,$.ajax()方法只要设置 dataType 属性即可加载 JSON 文件。而在非同域下,可以使用 JSONP,但也是有条件的。

//同一个域下$.ajax()加载 JSON 文件

 1 $.ajax({
 2 
 3     type : 'POST',
 4 
 5     url : 'test.json',
 6 
 7     dataType : 'json',
 8 
 9     success : function (response, status, xhr) {
10 
11         alert(response[0].url);
12 
13     }
14 
15 });

 

如果想跨域操作文件的话,我们就必须使用 JSONP。JSONP(JSON with Padding)是一个非官方的协议,它允许在服务器端集成 Script tags 返回至客户端,通过 javascript callback 的形式实现跨域访问(这仅仅是 JSONP 简单的实现形式) 。

//跨域的 PHP 端文件

 1 <?php
 2 
 3 $arr = array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
 4 
 5 $result = json_encode($arr);
 6 
 7 $callback = $_GET['callback'];
 8 
 9 echo $callback."($result)";
10 
11 ?>

 

 

//$.getJSON()方法跨域获取 JSON

$.getJSON('http://www.li.cc/test.php?callback=?', function (response) {

  console.log(response);

});

 

//$.ajax()方法跨域获取 JSON

 1 $.ajax({
 2 
 3     url : 'http://www.li.cc/test.php?callback=?',
 4 
 5     dataType : 'jsonp',        //这儿设置为jsonp那么上面一行可以不要  "?callback=?" 了 !
 6 
 7     success : function (response, status, xhr) {
 8 
 9         console.log(response);
10 
11         alert(response.a);
12 
13     }
14 
15 });

 

 

五.jqXHR 对象

在之前,我们使用了局部方法:.success()、.complete()和.error()。这三个局部方法并不是 XMLHttpRequest 对象调用的,而是$.ajax()之类的全局方法返回的对象调用的(见上面示例)。 这个对象就是 jqXHR 对象,它是原生对象 XHR 的一个超集。

//获取 jqXHR 对象,查看属性和方法

var jqXHR = $.ajax({

  type : 'POST',

  url : 'test.php',

  data : $('form').serialize()

});

for (var i in jqXHR) {

  document.write(i + '<br />');

}

 

PS:如果使用 jqXHR 对象的话,那么建议用.done()、.always()和.fail()代替.success()、.complete()和.error()。以为在未来版本中,很可能将这三种方法废弃取消。

//成功后回调函数

 1 var jqXHR = $.ajax({
 2 
 3     type : 'POST',
 4 
 5     url : 'test.php',
 6 
 7     data : $('form').serialize()
 8 
 9 });
10 
11  
12 
13 jqXHR.done(function (response) {
14 
15     $('#box').html(response);
16 
17 });

 

 

使用 jqXHR 的连缀方式比$.ajax()的属性方式有三大好处:

1.可连缀操作,可读性大大提高;

2.可以多次执行同一个回调函数;

3.为多个操作指定回调函数;

 

//同时执行多个成功后的回调函数

jqXHR.done().done();

 

//多个操作指定回调函数

test1.php文件:

<?php

         echo 'test1.php'

?>

test2.php文件:

<?php

         echo 'test2.php'

?>

var jqXHR1 = $.ajax('test1.php');

var jqXHR2 = $.ajax('test2.php');

//使用when方法同时处理多个,不需要每个都单独书写了!

$.when(jqXHR1, jqXHR2).done(function (r1,r2) {

alert(r1[0]);   //可以打印下r1看看结果

alert(r2[0]);

});

 

 

 For my Lover, C!

Thank you, MR. Lee !

 

 

 

 

posted @ 2014-06-25 20:15  努力就有机会  阅读(4357)  评论(3编辑  收藏  举报