亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

用原生JS對(duì)AJAX做簡(jiǎn)單封裝的實(shí)例代碼

 更新時(shí)間:2016年07月13日 10:21:28   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇用原生JS對(duì)AJAX做簡(jiǎn)單封裝的實(shí)例代碼。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

首先,我們需要xhr對(duì)象。這對(duì)我們來(lái)說(shuō)不難,封裝成一個(gè)函數(shù)。

var createAjax = function() { var xhr = null; try { //IE系列瀏覽器 xhr = new ActiveXObject("microsoft.xmlhttp");
  } catch (e1) { try { //非IE瀏覽器 xhr = new XMLHttpRequest();
    } catch (e2) { window.alert("您的瀏覽器不支持ajax,請(qǐng)更換!");
    }
  } return xhr;
}; 

然后,我們來(lái)寫(xiě)核心函數(shù)。

var ajax = function(conf) { // 初始化 //type參數(shù),可選 var type = conf.type; //url參數(shù),必填 var url = conf.url; //data參數(shù)可選,只有在post請(qǐng)求時(shí)需要 var data = conf.data; //datatype參數(shù)可選 var dataType = conf.dataType; //回調(diào)函數(shù)可選 var success = conf.success; if (type == null){ //type參數(shù)可選,默認(rèn)為get type = "get";
  } if (dataType == null){ //dataType參數(shù)可選,默認(rèn)為text dataType = "text";
  } // 創(chuàng)建ajax引擎對(duì)象 var xhr = createAjax(); // 打開(kāi) xhr.open(type, url, true); // 發(fā)送 if (type == "GET" || type == "get") {
    xhr.send(null);
  } else if (type == "POST" || type == "post") {
    xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    xhr.send(data);
  }
  xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if(dataType == "text"||dataType=="TEXT") { if (success != null){ //普通文本 success(xhr.responseText);
        }
      }else if(dataType=="xml"||dataType=="XML") { if (success != null){ //接收xml文檔 success(xhr.responseXML);
        } 
      }else if(dataType=="json"||dataType=="JSON") { if (success != null){ //將json字符串轉(zhuǎn)換為js對(duì)象 success(eval("("+xhr.responseText+")"));
        }
      }
    }
  };
}; 

最后,說(shuō)明一下此函數(shù)的用法。

 ajax({ type:"post",
    url:"test.jsp",
    data:"name=dipoo&info=good",
    dataType:"json",
    success:function(data){ alert(data.name); } }); 

以上這篇用原生JS對(duì)AJAX做簡(jiǎn)單封裝的實(shí)例代碼就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論