第一百七十四节,jQuery,Ajax进阶
jQuery,Ajax進(jìn)階
?
學(xué)習(xí)要點:
1.加載請求
2.錯誤處理
3.請求全局事件
4.JSON 和 JSONP
5.jqXHR 對象
?
在 Ajax 課程中,我們了解了最基本的異步處理方式。本章,我們將了解一下 Ajax 的 一些全局請求事件、跨域處理和其他一些問題。
?
一.加載請求
在 Ajax 異步發(fā)送請求時,遇到網(wǎng)速較慢的情況,就會出現(xiàn)請求時間較長的問題。而超 過一定時間的請求,用戶就會變得不再耐煩而關(guān)閉頁面。而如果在請求期間能給用戶一些提 示,比如:正在努力加載中...,那么相同的請求時間會讓用戶體驗更加的好一些。
jQuery 提供了兩個全局事件,.ajaxStart()和.ajaxStop()。這兩個全局事件,只要用戶觸發(fā) 了 Ajax,請求開始時(未完成其他請求)激活.ajaxStart(),請求結(jié)束時(所有請求都結(jié)束了) 激活.ajaxStop()。
ajaxStart()方法,請求開始時(未完成其他請求)激活.ajaxStart(),在document上使用,參數(shù)是匿名函數(shù),可以在函數(shù)里做請求時的提示和操作
ajaxStop()方法,請求結(jié)束時(所有請求都結(jié)束了)激活.ajaxStop(),在document上使用,參數(shù)是匿名函數(shù),可以在函數(shù)里做請求結(jié)束的提示和操作
?
如果請求時間太長,可以設(shè)置超時
//ajax請求$('form input[type=button]').click(function () {$.ajax({type: 'POST',url: 'http://www.test.php',data: $('form').serialize(),success: function (response, status, xhr) {$('#box').html(response);},timeout : 500 //如果請求時間太長,可以設(shè)置超時 });});//監(jiān)測ajax請求$(document).ajaxStart(function () { //未完成請求時$('span').show(); //顯示正在請求,請稍等}).ajaxStop(function () { //請求結(jié)束時$('span').hide(); //隱藏請求提示元素});?
如果某個 ajax 不想觸發(fā)全局事件,可以設(shè)置取消
//ajax請求$('form input[type=button]').click(function () {$.ajax({type: 'POST',url: 'http://www.test.php',data: $('form').serialize(),success: function (response, status, xhr) {$('#box').html(response);},global : false //如果某個 ajax 不想觸發(fā)全局事件,可以設(shè)置取消 });});//監(jiān)測ajax請求//global : false了就不會觸發(fā)這兩個事件了,這里就不起作用了$(document).ajaxStart(function () { //未完成請求時$('span').show(); //顯示正在請求,請稍等}).ajaxStop(function () { //請求結(jié)束時$('span').hide(); //隱藏請求提示元素});?
二.錯誤處理
Ajax 異步提交時,不可能所有情況都是成功完成的,也有因為代碼異步文件錯誤、網(wǎng) 絡(luò)錯誤導(dǎo)致提交失敗的。這時,我們應(yīng)該把錯誤報告出來,提醒用戶重新提交或提示開發(fā)者 進(jìn)行修補。
?在之前高層封裝中是沒有回調(diào)錯誤處理的,比如$.get()、$.post()和.load()。所以,早期 的方法通過全局.ajaxError()事件方法來返回錯誤信息。而在 jQuery1.5 之后,可以通過連綴 處理使用局部.error()方法即可。而對于$.ajax()方法,不但可以用這兩種方法,還有自己的屬 性方法 error : function () {}。
?
$.ajax()使用屬性提示錯誤,error : function () {}。
//ajax請求$('form input[type=button]').click(function () {$.ajax({type: 'POST',url: 'test.php',data: $('form').serialize(),success: function (response, status, xhr) {$('#box').html(response);},error: function (xhr, errorText, errorStatus) { //如果發(fā)生錯誤,返回錯誤信息alert(xhr.statusText + ':' + xhr.status);}});});?
error()方法提示錯誤
fail().方法將取代error(),請求失敗時調(diào)用的回調(diào)函數(shù),接收三個形式參數(shù)xhr, status, info
?
$.post()使用連綴.error()方法提示錯誤,連綴方法將被.fail()取代
$('form input[type=button]').click(function () {$.post('ttttest.php').error(function (xhr, status, info) { //如果出現(xiàn)錯誤打印錯誤信息alert(xhr.status + ':' + xhr.statusText);});});?
ajaxError()全局事件提示錯誤,在document上使用,參數(shù)是一個匿名函數(shù),函數(shù)接收4個形式參數(shù),event對象, xhr通訊對象, settings, infoError
$.post()使用全局.ajaxError()事件提示錯誤
//ajax請求$('form input[type=button]').click(function () {$.ajax({type: 'POST',url: 'test.php',data: $('form').serialize(),success: function (response, status, xhr) {$('#box').html(response);}});});//ajaxError()全局事件提示錯誤,在document上使用,參數(shù)是一個匿名函數(shù),函數(shù)接收4個形式參數(shù),event對象, xhr通訊對象, settings, infoError$(document).ajaxError(function (event, xhr, settings, infoError) {alert(xhr.status + ':' + xhr.statusText);alert(settings + ':' + infoError);});?
三.請求全局事件
jQuery 對于 Ajax 操作提供了很多全局事件方法,.ajaxStart()、.ajaxStop()、.ajaxError() 等事件方法。他們都屬于請求時觸發(fā)的全局事件,除了這些,還有一些其他全局事件:
注意:全局事件方法是所有 Ajax 請求都會觸發(fā)到,并且只能綁定在 document 上。而局 部方法,則針對某個 Ajax。 對于一些全局事件方法的參數(shù),大部分為對象,而這些對象有哪些屬性或方法能調(diào)用, 可以通過遍歷方法得到。
?
ajaxSuccess(),對應(yīng)一個局部方法:.success(),請求成功完成時執(zhí)行。請求成功時執(zhí)行
//$.post()使用全局事件方法.ajaxSuccess()$('form input[type=button]').click(function () {$.post('test.php', $('form').serialize(), function (response, status, xhr) {$('#box').html(response);});});//使用全局事件方法.ajaxSuccess()$(document).ajaxSuccess(function (event, xhr, settings) {alert(xhr.responseText);});success()Ajax局部方法,請求成功完成時執(zhí)行。請求成功時執(zhí)行
done().方法將取代success(),請求成功后調(diào)用的回調(diào)函數(shù),接收三個形式參數(shù)response, status, xhr【推薦】
//$.post()使用局部方法.success()$('form input[type=button]').click(function () {$.post('test.php', $('form').serialize(), function (response, status, xhr) {$('#box').html(response);}).success(function (response, status, xhr) { //success()Ajax局部方法,請求成功完成時執(zhí)行。請求成功時執(zhí)行 alert(response);});});?
?
ajaxComplete(),對應(yīng)一個局部方法:.complete(),請求完成后注冊一個回調(diào)函數(shù)。請求完成無論成功失敗都執(zhí)行
$('form input[type=button]').click(function () {$.post('test.php', $('form').serialize(), function (response, status, xhr) {alert('成功');});});//$.post()請求完成的全局方法.ajaxComplete()$(document).ajaxComplete(function (event, xhr, settings) {alert('完成');});complete()Ajax局部方法,請求完成無論成功失敗都執(zhí)行
always().方法將取代complete(),請求完成后調(diào)用的回調(diào)函數(shù),接收三個形式參數(shù)response, status, xhr【推薦】
//$.post()請求完成的局部方法.complete()$('form input[type=button]').click(function () {$.post('test.php', $('form').serialize(), function (response, status, xhr) {alert('成功');}).complete(function (xhr, status) { //complete()Ajax局部方法,請求完成無論成功失敗都執(zhí)行alert('完成');});});?
ajaxSend(),沒有對應(yīng)的局部方法,只有屬性 beforeSend,請求發(fā)送之前要綁定的函數(shù)。請求之前執(zhí)行
$('form input[type=button]').click(function () {$.post('test.php', $('form').serialize(), function (response, status, xhr) {alert('成功');});});//$.post()請求發(fā)送之前的全局方法.ajaxSend()$(document).ajaxSend(function (event, xhr, settings) {alert('發(fā)送請求之前');});beforeSend,Ajax局部屬性,請求之前執(zhí)行
//$.ajax()方法,可以直接通過屬性設(shè)置即可。$('form input[type=button]').click(function () {$.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) { //beforeSend,Ajax局部屬性,請求之前執(zhí)行alert('請求之前' + ' - ' + xhr.readyState + ' - ' + settings.url);}});});?注意:在 jQuery1.5 版本以后,使用.success()、.error()和.complete()連綴的方法,可以 用.done()、.fail()和.always()取代。
?
四.JSON 和 JSONP
如果在同一個域下,$.ajax()方法只要設(shè)置 dataType 屬性即可加載 JSON 文件。而在非 同域下,可以使用 JSONP,但也是有條件的。
ajax()同一個域下加載 JSON 文件
$('form input[type=button]').click(function () {$.ajax({type: 'POST',url: 'test.json',dataType: 'json',success: function (response, status, xhr) {alert(response[0].url);}});});?
如果想跨域操作文件的話,我們就必須使用 JSONP。JSONP(JSON with Padding)是一個 非官方的協(xié)議,它允許在服務(wù)器端集成 Script tags 返回至客戶端,通過 javascript callback 的 形式實現(xiàn)跨域訪問(這僅僅是 JSONP 簡單的實現(xiàn)形式)。
跨域的 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: 'json', //必須指定類型success: function (response, status, xhr) {console.log(response);alert(response.a);}});注意:跨域獲取必須傳遞契約
?
JSONP,數(shù)據(jù)類型dataType: 'jsonp',這種類型不需要傳遞契約【重點】
//跨域獲取 JSON$('form input[type=button]').click(function () {$.ajax({type: 'POST',url: 'http://www.li.cc/test.php',dataType: 'jsonp', //JSONP,數(shù)據(jù)類型dataType: 'jsonp',這種類型不需要傳遞契約success: function (response, status, xhr) {alert(response);}});});?
五.jqXHR 對象【推薦】
在之前,我們使用了局部方法:.success()、.complete()和.error()。這三個局部方法并不 是 XMLHttpRequest 對象調(diào)用的,而是$.ajax()之類的全局方法返回的對象調(diào)用的。這個對象, 就是 jqXHR 對象,它是原生對象 XHR 的一個超集。
jqXHR就是$.ajax()返回的本身對象
$('form input[type=button]').click(function () {var jqXHR = $.ajax({type: 'POST',url: 'test.php',data: $('form').serialize() //表單序列化 });//此時的jqXHR就是ajax的返回對象,后面還可以連綴jqXHR.done(function (response, status, xhr) {alert(response + '1')}).done(function (response, status, xhr) {alert(response + '2')});});?
注意:如果使用 jqXHR 對象的話,那么建議用.done()、.always()和.fail()代 替.success()、.complete()和.error()。以為在未來版本中,很可能將這三種方法廢棄取消。
done().方法將取代success(),請求成功后調(diào)用的回調(diào)函數(shù),接收三個形式參數(shù)response, status, xhr
always().方法將取代complete(),請求完成后調(diào)用的回調(diào)函數(shù),接收三個形式參數(shù)response, status, xhr
fail().方法將取代error(),請求失敗時調(diào)用的回調(diào)函數(shù),接收三個形式參數(shù)xhr, status, info
?
使用 jqXHR 的連綴方式比$.ajax()的屬性方式有三大好處: 1.可連綴操作,可讀性大大提高; 2.可以多次執(zhí)行同一個回調(diào)函數(shù); 3.為多個操作指定回調(diào)函數(shù);
?
多個操作指定回調(diào)函數(shù)
when()全局方法,可以接收多個jqXHR對象處理,參數(shù)是要處理的,jqXHR對象,在方法的匿名函數(shù)里接收處理
var jqXHR = $.ajax('test.php');var jqXHR2 = $.ajax('test2.php');$.when(jqXHR, jqXHR2).done(function (r1, r2) {alert(r1[0]);alert(r2[0]);});?
轉(zhuǎn)載于:https://www.cnblogs.com/adc8868/p/6528055.html
超強干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的第一百七十四节,jQuery,Ajax进阶的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#设计模式(3)——工厂方法模式
- 下一篇: 官网3.15课程一起来“打价”,找群内管