jQuery基礎---Ajax進階

來源:互聯網
上載者:User

標籤:style   class   blog   code   http   java   

原文: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 !

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.