您的位置:首页 > 其它

Ajax 进阶

2015-12-25 16:15 204 查看
学习要点:

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();

});

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

$(document).ajaxStart(function () {

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

}).ajaxStop(function () {

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

});

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

$.ajax({

timeout : 500

});

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

$.ajax({

global : false

});

二.错误处理

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

在之前ÉÊËÌ中是Í有ÎÏ错误处理的,比如$.get()、$.post()和.load()。所以,Ð期 的方ÑÒ过全局.ajaxError()事件方Ñ来ÓÎ错误ÔÕ。而在 jQuery1.5 之后,可以Ò过Ö× 处理使用局Ø.error()方ÑÙ可。而对Ú$.ajax()方Ñ,不Û可以用这两Ü方Ñ,Ý有Þß的à á方Ñ error : function () {}。

//$.ajax()使用àá提示错误

$.ajax({

type : 'POST', url : 'test1.php',

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

success : function (response, status, xhr) {

$('#box').html(response);

},

error : function (xhr, errorText, errorStatus) {

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

}

});

//$.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, infoError) {

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

alert(settings+ ':' + info);

});

ã.请求全局事件

jQuery 对Ú Ajax ä作提供了åæ全局事件方Ñ,.ajaxStart()、.ajaxStop()、.ajaxError()

ç事件方Ñ。他们都àÚ请求时触发的全局事件,è了这些,Ý有一些其他全局事件:

.ajaxSuccess(),对应一个局Ø方Ñ:.success(),请求成功完成时é行。

.ajaxComplete(),对应一个局Ø方Ñ:.complete(),请求完成后注ê一个ÎÏëì。

.ajaxSend(),Í有对应的局Ø方Ñ,只有àá beforeSend,请求发送之前要绑定的ëì。

//$.post()使用局Ø方Ñ.success()

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

$('#box').html(response);

}).success(function (response, status, xhr) {

alert(response);

});

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

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

alert(xhr.responseText);

});

注意:全局事件方Ñ是所有 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({

type : 'POST', url : 'test.php',

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

success : function (response, status, xhr) {

$('#box').html(response);

},

complete : function (xhr, status) {

alert('完成' + ' - ' + xhr.responseText + ' - ' + status);

},

beforeSend : function (xhr, settings) {

alert('请求之前' + ' - ' + xhr.readyState + ' - ' + settings.url);

}

});

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

ù.JSON JSONP

如果在同一个域下,$.ajax()方Ñ只要设置 dataType àáÙ可加载 JSON 文件。而在ú

同域下,可以使用 JSONP,Û也是有û件的。

//$.ajax()加载 JSON 文件

$.ajax({

type : 'POST', url : 'test.json', dataType : 'json',

success : function (response, status, xhr) {

alert(response[0].url);

}

});

如果想跨域ä作文件的ü,我们就必须使用 JSONP。JSONP(JSON with Padding)是一个 ú官方的ýþ,ÿĀā在Ă㥹Ć成 Script tags ÓÎćĈ户ą,Ò过 javascript callback 的 ĉ式Ċ现跨域ċ问(这ČČ是 JSONP čĎ的Ċ现ĉ式)。

//跨域的 PHP ą文件

<?php

$arr = array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

$result = json_encode($arr);

$callback = $_GET['callback'];

echo $callback."($result)";

?>

//$.getJSON()方Ñ跨域ď取 JSON

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

console.log(response);

});

//$.ajax()方Ñ跨域ď取 JSON

$.ajax({

url : 'http://www.li.cc/test.php?callback=?', dataType : 'jsonp',

success : function (response, status, xhr) {

console.log(response);

alert(response.a);

}

});

Đ.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 />');

}

注意:如果使用 jqXHR 对象的ü,那么Ėþ用.done()、.always()和.fail()代

ė.success()、.complete()和.error()。以为在未来版本中,å可能将这ãÜ方ÑĘę取消。

//成功后ÎÏëì

jqXHR.done(function (response) {

$('#box').html(response);

});

使用 jqXHR 的Ö×方式比$.ajax()的àá方式有ãò好处:

1.可Ö×ä作,可Ěáòò提Éě

2.可以æĜé行同一个ÎÏëìě

3.为æ个ä作ĝ定ÎÏëìě

//同时é行æ个成功后的ÎÏëì

jqXHR.done().done();

//æ个ä作ĝ定ÎÏëì

var jqXHR = $.ajax('test.php');

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

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

alert(r1[0]);

alert(r2[0]);

});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: