欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery ajax的功能實(shí)現(xiàn)方法詳解

 更新時(shí)間:2017年01月06日 10:49:48   作者:_記憶  
jQuery的ajax方法非常好用,這么好的東西,你想擁有一個(gè)屬于自己的ajax么?接下來(lái),我們來(lái)自己做一個(gè)簡(jiǎn)單的ajax吧

jQuery的ajax方法非常好用,這么好的東西,你想擁有一個(gè)屬于自己的ajax么?接下來(lái),我們來(lái)自己做一個(gè)簡(jiǎn)單的ajax吧。

實(shí)現(xiàn)功能

由于jq中的ajax方法是用了內(nèi)置的deferred模塊,是Promise模式的一種實(shí)現(xiàn),而我們這里沒(méi)有講過(guò),所以我們就不使用這一模式啦。

我們只定義一個(gè)ajax方法,他可以簡(jiǎn)單的get,post,jsonp請(qǐng)求就可以啦~~

var ajax = function () {
 // 做一些初始化,定義一些私有函數(shù)等
 return function () {
 // ajax主體代碼
 }
}()
ajax({
 url: myUrl,
 type: 'get',
 dataType: 'json',
 timeout: 1000,
 success: function (data, status) {
 console.log(data)
 },
 fail: function (err, status) {
 console.log(err)
 }
})

我們的ajax方法最后實(shí)現(xiàn)的功能如上所示,非常類似于jq。那我們還在等什么,開始吧。

整體思路

我們的ajax方法需要傳遞一個(gè)對(duì)象進(jìn)去,這個(gè)對(duì)象中我們可以定義一些我們希望的屬性,我們就必須初始一下各種屬性

//默認(rèn)請(qǐng)求參數(shù)
 var _options = {
 url: null, // 請(qǐng)求連接
 type: 'GET', // 請(qǐng)求類型
 data: null, // post時(shí)請(qǐng)求體
 dataType: 'text', // 返回請(qǐng)求的類型,有text/json兩種
 jsonp: 'callback', // jsonp請(qǐng)求的標(biāo)志,一般不改動(dòng)
 jsonpCallback: 'jsonpCallback', //jsonp請(qǐng)求的函數(shù)名
 async: true, // 是否異步
 cache: true, // 是否緩存
 timeout:null, // 設(shè)置請(qǐng)求超時(shí)
 contentType: 'application/x-www-form-urlencoded',
 success: null, // 請(qǐng)求成功回調(diào)函數(shù)
 fail: null // 請(qǐng)求失敗回調(diào)
 }

以上我們定義了一大串請(qǐng)求有關(guān)的數(shù)據(jù),接下來(lái)我們就開始ajax主體函數(shù)的書寫,現(xiàn)在的ajax方法是這樣了

var ajax = function () {
 //默認(rèn)請(qǐng)求參數(shù)
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // ...
 return function (options) {
  // ...
 }
}()

我們可以想一下,ajax方法傳遞一個(gè)對(duì)象進(jìn)來(lái),我們是不是需要把我們?cè)O(shè)置的這個(gè)對(duì)象上的屬性來(lái)覆蓋掉初始化_options上面的那些屬性呢,肯定需要。那下面我們先寫一個(gè)簡(jiǎn)單的繼承,如下:

var ajax = function () {
 //默認(rèn)請(qǐng)求參數(shù)
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // 內(nèi)部使用的繼承方法
 var _extend = function(target,options) {
 if( typeof target !== 'object' || typeof options !== 'object' ) {
  return;
 }
 var copy ,clone, name;
 for( name in options ) {
  if(options.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
  target[name] = options[name];
  }
 }
 return target;
 };
 // ...
 return function (options) {
 // 沒(méi)有傳參或者沒(méi)有url,拋出錯(cuò)誤
 if( !options || !options.url ) {
  throw('參數(shù)錯(cuò)誤!');
 }
 // 繼承操作
 options.type = options.type.toUpperCase();
 _extend(options,_options);
  // ...
 }
}()

這個(gè)繼承方法,我們是把初始化的_options繼承到了options,為什么呢?因?yàn)槲覀冞@個(gè)_options對(duì)象不在ajax方法內(nèi)部,我們需要使用它,但我們不能改變他,如果改變了他,下一次使用ajax方法將會(huì)崩潰。因此,我們緊緊是把配置的options對(duì)象沒(méi)有的屬性設(shè)置為初始值。

下面,我們就要發(fā)送請(qǐng)求了么?等等!好像jsonp請(qǐng)求不是xhr請(qǐng)求啊,他好像是將請(qǐng)求url當(dāng)做script標(biāo)簽的src值插入到頁(yè)面body中去實(shí)現(xiàn)的,哦,對(duì)了,我們先把jsonp請(qǐng)求處理一下再開始建立xhr請(qǐng)求的代碼吧。

var ajax = function () {
 //默認(rèn)請(qǐng)求參數(shù)
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // 內(nèi)部使用的繼承方法
 var _extend = function(target,options) {
 if( typeof target !== 'object' || typeof options !== 'object' ) {
  return;
 }
 var copy ,clone, name;
 for( name in options ) {
  if(options.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
  target[name] = options[name];
  }
 }
 return target;
 };
 // jsonp處理函數(shù)
 function _sendJsonpRequest(url,callbackName,succCallback) {
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src=url;
 document.body.appendChild(script);
 // 如果用戶自己定義了回調(diào)函數(shù),就用自己定義的,否則,調(diào)用success函數(shù)
 window[callbackName] = window[callbackName] || succCallback;
 }
 // ...
 return function (options) {
 // 沒(méi)有傳參或者沒(méi)有url,拋出錯(cuò)誤
 if( !options || !options.url ) {
  throw('參數(shù)錯(cuò)誤!');
 }
 // 繼承操作
 options.type = options.type.toUpperCase();
 _extend(options,_options);
 /*jsonp部分,直接返回*/
 if( options.dataType === 'jsonp' ) {
  var jsonpUrl = options.url.indexOf('?') > -1 ? options.url: options.url +
  '?' + options.jsonp+ '=' + options.jsonpCallback;
  return _sendJsonpRequest(jsonpUrl,options.jsonpCallback,options.success);
 }
  // ...
 }
}()

我們定義了一個(gè)_sendJsonpRequest函數(shù),這個(gè)函數(shù)接收三個(gè)參數(shù),第一個(gè)是jsonpUrl,第二個(gè)是jsonp的回調(diào)函數(shù)名,第三個(gè)是成功回調(diào)函數(shù),我們?cè)谶@個(gè)函數(shù)內(nèi)建立一個(gè)src為jsonpUrl的script元素插入到body中,同時(shí),確定了回調(diào)函數(shù)(如果我們定義了jsonpCallback函數(shù)就調(diào)用它,如果沒(méi)有就調(diào)用success回調(diào),一般情況我們不去定義全局的jsonpCallback函數(shù)而傳遞success回調(diào)來(lái)完成jsonp請(qǐng)求)。

好,處理好jsonp請(qǐng)求后,我們開始處理xhr請(qǐng)求了。

var ajax = function () {
 //默認(rèn)請(qǐng)求參數(shù)
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // 內(nèi)部使用的繼承方法
 var _extend = function(target,options) {
 if( typeof target !== 'object' || typeof options !== 'object' ) {
  return;
 }
 var copy ,clone, name;
 for( name in options ) {
  if(options.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
  target[name] = options[name];
  }
 }
 return target;
 };
 // jsonp處理函數(shù)
 function _sendJsonpRequest(url,callbackName,succCallback) {
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src=url;
 document.body.appendChild(script);
 // 如果用戶自己定義了回調(diào)函數(shù),就用自己定義的,否則,調(diào)用success函數(shù)
 window[callbackName] = window[callbackName] || succCallback;
 }
 // json轉(zhuǎn)化為字符串
 var _param = function(data) {
 var str = '';
 if( !data || _empty(data)) {
  return str;
 }
 for(var key in data) {
  str += key + '='+ data[key]+'&'
 }
 str = str.slice(0,-1);
 return str;
 }
 //判斷對(duì)象是否為空
 var _empty = function(obj) {
 for(var key in obj) {
  return false;
 }
 return true;
 }
 // ...
 return function (options) {
 // 沒(méi)有傳參或者沒(méi)有url,拋出錯(cuò)誤
 if( !options || !options.url ) {
  throw('參數(shù)錯(cuò)誤!');
 }
 // 繼承操作
 options.type = options.type.toUpperCase();
 _extend(options,_options);
 /*jsonp部分,直接返回*/
 if( options.dataType === 'jsonp' ) {
  var jsonpUrl = options.url.indexOf('?') > -1 ? options.url: options.url +
  '?' + options.jsonp+ '=' + options.jsonpCallback;
  return _sendJsonpRequest(jsonpUrl,options.jsonpCallback,options.success);
 }
  //XMLHttpRequest傳參無(wú)影響
 var xhr = new (window.XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
 // get搜索字符串
 var search = '';
 // 將data序列化
 var param= _param(options.data)
 if( options.type === 'GET' ) {
  search = (options.url.indexOf('?') > -1 ? '&' : '?') + param;
  if(!options.cache) {
  search += '&radom='+Math.random();
  }
  param = null;
 }
  // ...
 }
}()

首先,兼容ie創(chuàng)建xhr對(duì)象,XMLHttpRequest構(gòu)造函數(shù)傳遞參數(shù)是無(wú)影響,然后我們定義了兩個(gè)輔助變量:search、param,前者用于get請(qǐng)求的查詢字串,后者用于post請(qǐng)求的send內(nèi)容,我們定義了一個(gè)_param方法來(lái)講對(duì)象轉(zhuǎn)換為send方法參數(shù)的模式,就如你看到的那樣,下面我們做了get與post之間合理的search、param的賦值工作。接下來(lái)我們就可以發(fā)送請(qǐng)求書寫最激動(dòng)人心的內(nèi)容了。

最終的代碼如下

;
var ajax = function () {
 //默認(rèn)請(qǐng)求參數(shù)
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // json轉(zhuǎn)化為字符串
 var _param = function(data) {
 var str = '';
 if( !data || _empty(data)) {
  return str;
 }
 for(var key in data) {
  str += key + '='+ data[key]+'&'
 }
 str = str.slice(0,-1);
 return str;
 }
 //判斷對(duì)象是否為空
 var _empty = function(obj) {
 for(var key in obj) {
  return false;
 }
 return true;
 }
 var _extend = function(target,options) {
 if( typeof target !== 'object' || typeof options !== 'object' ) {
  return;
 }
 var copy ,clone, name;
 for( name in options ) {
  if(options.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
  target[name] = options[name];
  }
 }
 return target;
 };
 // 自定義text轉(zhuǎn)化json格式
 var parseJSON = function(text) {
 if(typeof text !== 'string') {
  return;
 }
 if( JSON && JSON.parse ) {
  return JSON.parse(text);
 }
 return (new Function('return '+text))();
 }
 // jsonp處理函數(shù)
 function _sendJsonpRequest(url,callbackName,succCallback) {
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src=url;
 document.body.appendChild(script);
 // 如果用戶自己定義了回調(diào)函數(shù),就用自己定義的,否則,調(diào)用success函數(shù)
 window[callbackName] = window[callbackName] || succCallback;
 }
 return function (options) {
 // 沒(méi)有傳參或者沒(méi)有url,拋出錯(cuò)誤
 if( !options || !options.url ) {
  throw('參數(shù)錯(cuò)誤!');
 }
 // 繼承操作
 options.type = options.type.toUpperCase();
 _extend(options,_options);
 /*jsonp部分,直接返回*/
 if( options.dataType === 'jsonp' ) {
  var jsonpUrl = options.url.indexOf('?') > -1 ? options.url: options.url +
  '?' + options.jsonp+ '=' + options.jsonpCallback;
  _sendJsonpRequest(jsonpUrl,options.jsonpCallback,options.success);
  return;
 }
  //XMLHttpRequest傳參無(wú)影響
 var xhr = new (window.XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
 // get搜索字符串
 var search = '';
 // 將data序列化
 var param= _param(options.data)
 if( options.type === 'GET' ) {
  search = (options.url.indexOf('?') > -1 ? '&' : '?') + param;
  if(!options.cache) {
  search += '&radom='+Math.random();
  }
  param = null;
 }
 xhr.open( options.type, options.url + search, options.async );
 xhr.onreadystatechange = function() {
  if( xhr.readyState == 4 ) {
  if( xhr.status >= 200 && xhr.status < 300 || xhr.status == 304 ) {
   var text = xhr.responseText;
   // json格式轉(zhuǎn)換
   if(options.dataType == 'json') {
    text = parseJSON(text)
   }
   if( typeof options.success === 'function') {
   options.success(text,xhr.status)
   }
  }else {
   if(typeof options.fail === 'function') {
   options.fail('獲取失敗', 500)
   }
  }
  }
 }
 xhr.setRequestHeader('content-type',options.contentType);
 // get請(qǐng)求時(shí)param時(shí)null
 xhr.send(param);
 // 如果設(shè)置了超時(shí),就定義
 if(typeof options.timeout === 'number') {
  // ie9+
  if( xhr.timeout ) {
  xhr.timeout = options.timeout;
  }else {
  setTimeout(function() {
   xhr.abort();
  },options.timeout)
  }
 }
 }
}()

可以看到,我們很熟悉的xhr代碼,在這里,我們需要寫一個(gè)解析返回字串形成json格式對(duì)象的方法parseJSON,類似于jq中的parseJSON方法,如上所示。

我們還需要設(shè)置超時(shí)代碼,如果設(shè)置了請(qǐng)求超時(shí),我們就如上定義。

注意:上面代碼中,由于懶,設(shè)置請(qǐng)求頭一行并沒(méi)有判斷是否在post請(qǐng)求下,你可以自己設(shè)置~~~。

結(jié)尾

一個(gè)簡(jiǎn)單的ajax方法就完成了,你是否也完成了呢?如果你懂deferred,你可以嘗試著書寫為deferred格式,很簡(jiǎn)單的~~~。

以上所述是小編給大家介紹的jQuery ajax的功能實(shí)現(xiàn)方法詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • jQuery Validation插件remote驗(yàn)證方式的Bug解決

    jQuery Validation插件remote驗(yàn)證方式的Bug解決

    jQuery插件很多,其中一個(gè)重要的插件便是jQuery Validation,它的作用是對(duì)表單進(jìn)行驗(yàn)證,還上了jQuery官網(wǎng)。
    2010-07-07
  • jQuery 選擇器詳解

    jQuery 選擇器詳解

    這篇文章主要介紹了jQuery 選擇器詳解,圖文并茂,十分不錯(cuò),需要的朋友可以參考下
    2015-01-01
  • jquery實(shí)現(xiàn)簡(jiǎn)單每周輪換的日歷

    jquery實(shí)現(xiàn)簡(jiǎn)單每周輪換的日歷

    這篇文章主要為大家詳細(xì)介紹了jquery實(shí)現(xiàn)簡(jiǎn)單每周輪換的日歷,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-09-09
  • jQuery實(shí)現(xiàn)仿QQ在線客服效果的滾動(dòng)層代碼

    jQuery實(shí)現(xiàn)仿QQ在線客服效果的滾動(dòng)層代碼

    這篇文章主要介紹了jQuery實(shí)現(xiàn)仿QQ在線客服效果的滾動(dòng)層代碼,可實(shí)現(xiàn)實(shí)時(shí)讀取屏幕高度并顯示的功能,涉及jQuery響應(yīng)滾動(dòng)事件及定時(shí)操作的相關(guān)技巧,需要的朋友可以參考下
    2015-10-10
  • jquery對(duì)象與DOM對(duì)象轉(zhuǎn)化

    jquery對(duì)象與DOM對(duì)象轉(zhuǎn)化

    本文主要介紹了jquery對(duì)象與DOM對(duì)象轉(zhuǎn)化方法。具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧
    2017-02-02
  • jQuery解析json格式數(shù)據(jù)示例

    jQuery解析json格式數(shù)據(jù)示例

    這篇文章主要介紹了jQuery解析json格式數(shù)據(jù),涉及jQuery針對(duì)json格式數(shù)據(jù)元素遍歷相關(guān)操作技巧,需要的朋友可以參考下
    2018-09-09
  • jQuery元素選擇器用法實(shí)例

    jQuery元素選擇器用法實(shí)例

    這篇文章主要介紹了jQuery元素選擇器用法,通過(guò)一個(gè)簡(jiǎn)單的隱藏div元素實(shí)例講述了元素選擇器的用法,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2014-12-12
  • 可兼容IE的獲取及設(shè)置cookie的jquery.cookie函數(shù)方法

    可兼容IE的獲取及設(shè)置cookie的jquery.cookie函數(shù)方法

    在使用IE來(lái)測(cè)試的時(shí)候,發(fā)現(xiàn)Discuz中的common.js里面的getcookie和setcookie這兩個(gè)方法子啊IE下不起作用,因此有了jquery.cookie.js的由來(lái),感興趣的朋友可以參考下
    2013-09-09
  • jquery實(shí)現(xiàn)數(shù)字輸入框

    jquery實(shí)現(xiàn)數(shù)字輸入框

    本文主要分享了jquery實(shí)現(xiàn)數(shù)字輸入框的示例代碼,具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧
    2017-02-02
  • jQuery中的select操作詳解

    jQuery中的select操作詳解

    這篇文章主要介紹了jQuery中的select操作詳解的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-11-11

最新評(píng)論