不如封裝一個(gè)原生Ajax
封裝原生Ajax
我們常常引用jq就是為了使用上面的ajax,方便又實(shí)用。但是jq文件一個(gè)高達(dá)幾十kb,還有近幾年jq的發(fā)展趨勢(shì)不容樂(lè)觀,jq中還遲遲沒(méi)有改進(jìn)。于是自己造輪子,下面封裝了原生JS ajax 。你可以直接復(fù)制拿過(guò)來(lái)用。
function ajax(obj) {
// 對(duì)實(shí)參處理
obj = obj || {};
// 定義局部變量
var xmlhttp, type, url, async, dataType, data;
// 默認(rèn)type為GET
type = obj.type || 'GET';
type = trim(type).toUpperCase();
// 接口
url = obj.url
url = trim(url);
// 默認(rèn)為異步請(qǐng)求
async = obj.async || true;
// 設(shè)置跨域
dataType = obj.dataType || 'HTML';
dataType = trim(dataType).toUpperCase();
// 發(fā)送參數(shù)
data = obj.data || {};
// 刪除左右空格
function trim(str) {
return str.replace(/^\s+|\s+$/g, "");
};
// 定義格式化參數(shù)函數(shù)
var formatParams = function () {
if (typeof (data) == "object") {
var str = "";
for (var pro in data) {
str += pro + "=" + data[pro] + "&";
}
data = str.substr(0, str.length - 1);
}
if (type == 'GET' || dataType == 'JSONP') {
if (url.lastIndexOf('?') == -1) {
url += '?' + data;
} else {
url += '&' + data;
}
}
}
// 第一步,創(chuàng)建xmlhttprequest對(duì)象用來(lái)和服務(wù)器交換數(shù)據(jù)。
if (window.XMLHttpRequest) {
//Chrome || Firefox
xmlhttp = new XMLHttpRequest();
} else {
//IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 跨域請(qǐng)求
if (dataType == 'JSONP') {
if (typeof (obj.beforeSend) == 'function') obj.beforeSend(xmlhttp);
var callbackName = ('jsonp_' + Math.random()).replace(".", "");
var oHead = document.getElementsByTagName('head')[0];
data.callback = callbackName;
var ele = document.createElement('script');
ele.type = "text/javascript";
ele.onerror = function () {
console.log('failed');
obj.error && obj.error("failed");
};
oHead.appendChild(ele);
window[callbackName] = function (json) {
oHead.removeChild(ele);
window[callbackName] = null;
obj.success && obj.success(json);
};
formatParams();
ele.src = url;
return;
} else {
formatParams();
// 第二步,打開(kāi)鏈接
xmlhttp.open(type, url, async);
// 設(shè)置響應(yīng)頭
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
if (typeof (obj.beforeSend) == 'function') obj.beforeSend(xmlhttp);
// 第三步,發(fā)送請(qǐng)求
xmlhttp.send(data);
// 第四步,響應(yīng)處理
xmlhttp.onreadystatechange = function () {
if (xmlhttp.status != 200) {
console.log(xmlhttp.status + 'failed');
obj.error && obj.error(xmlhttp.status + 'failed');
return;
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (dataType == 'JSON') {
try {
res = JSON.parse(xmlhttp.responseText);
} catch (e) {
console.log('json格式錯(cuò)誤');
obj.error('json格式錯(cuò)誤');
}
} else if (dataType == 'XML') {
res = xmlhttp.responseXML;
} else {
res = xmlhttp.responseText;
}
obj.success && obj.success(res);
}
}
}
}
上面是封裝Ajax的js代碼。
下面是一個(gè)示例代碼。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>封裝原生js_Ajax</title>
<style>
#btn{ font-size:20px; padding:10px; }
</style>
</head>
<body>
<button id="btn" onclick="myFunction()">請(qǐng)求數(shù)據(jù)</button>
</body>
<script src="./ajax.js"></script>
<script>
var btn=document.querySelector("#btn");
var url="https://free-api.heweather.com/v5/weather?city=qingdao&key=18c650b4fad546ac9d384e6858526267";//示例網(wǎng)址
var url1="http://192.168.2.62/test5.php/";//測(cè)試網(wǎng)址
function myFunction(){
ajax({
url: url,
type: "get",
dataType: "json",
success: function(data) {
var list = data;
console.log(list);},
error: function(err) {
alert('請(qǐng)求數(shù)據(jù)失敗');
}
})
}
</script>
</html>
作者:Vam的金豆之路
主要領(lǐng)域:前端開(kāi)發(fā)
我的微信:maomin9761
微信公眾號(hào):前端歷劫之路