Ajax原生代码:
// 对象浅复制
function extend(dst,obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
dst[i] = obj[i];
}
}
}
function json(options) {
var opt = {
url: '',type: 'GET',data: {},success: function () {},error: function () {}
}
extend(opt,options);
if (opt.url) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft XMLHTTP');
var url = opt.url,type = opt.type,data = opt.data,dataArr = [];
for (var k in data) {
dataArr.push(k + "=" + data[k]);
}
if (type === "GET") {
url = url + "?" + dataArr.join("&");
xhr.open(type,url,true);
xhr.send();
}
if (type === "POST") {
xhr.open(type,true);
xhr.setRequestHeader('Content-type','application/x-www-form-rulencoded');
xhr.send(dataArr.join('&'));
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var res
if (xhr.status === 200 || xhr.status === 304) {
if (opt.success && opt.success instanceof Function) {
res = xhr.responseText;
if (typeof res === 'string') {
res = JSON.parse(res);
}
opt.success.call(xhr,res);
}
} else {
if (opt.error && opt.error instanceof Function) {
opt.error.call(xhr,res);
}
}
}
}
}
}
测试:
var options = {
url: 'https://free-api.heweather.com/s6/weather/forecast',data: {
location: 'beijing',key: '5dafd138ca9841938affbd41798d1cbb'
},success: function (res) {
console.log('success');
console.log(res);
},error: function (res) {
console.log('error');
console.log(res);
}
}
json(options);