ajax和jQuery封装的ajax
ajax:异步的javascript和xml
// 1.创建AJAX实例对象
let xhr ;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest;
}else{
//为了兼容IE5、6
xhr=new ActiveXObject('Microsoft.XMLHTTP');
}
// 2.打开URL(发送请求前的处理)
xhr.open(method, url, async); //true 为异步
// 3.监听AJAX的状态信息
xhr.onreadystatechange = function () {
// xhr.readyState AJAX的状态 0-4 xhr.status服务器返回的网络状态码
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);//获得字符串形式的响应数据
console.log(xhr.responseXML);//获得xml形式的响应数据
}
}
// 4.发送请求(请求主体的信息会基于send的时候发送给服务器)
xhr.send(); //如果是post请求,可以传参string
jQuery封装ajax
function ajax() {
var ajaxData = {
type: (arguments[0].type || 'GET').toUpperCase(),
url: arguments[0].url || '',
async: arguments[0].async || 'true',
data: arguments[0].data || '',
dataType: arguments[0].dataType || 'json',
contentType: arguments[0].contentType || 'application/x-www-form-urlencoded; charset=utf-8',
beforeSend: arguments[0].beforeSend || function () { },
success: arguments[0].success || function () { },
error: arguments[0].error || function () { }
}
ajaxData.beforeSend()
let xhr = createXmlHttpRequest();
xhr.responseType = ajaxData.dataType;
//判断请求方式
let params = {};
for (let key in ajaxData.data) {
let temp = key + '=' + data[key];
params.push(temp);
}
let sendData = params.join('&'); //get请求传递的数据
if (ajaxData.type === 'GET') {
xhr.open('GET', ajaxData.url + "?" + sendData, ajaxData.async);
xhr.send(null);
} else if (ajaxData.type === 'POST') {
xhr.open('POST', ajaxData.url, ajaxData.async);
xhr.setRequestHeader('Content-Type', ajaxData.contentType)
xhr.send(convertDate(ajaxData.data));
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
ajaxData.success(xhr.response)
} else {
ajaxData.error()
}
}
function createXmlHttpRequest() {
let xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
return xhr;
}
function convertDate(data) {
//对象转为字符串{name:"张三",age:13}==> name=张三&age=13
if (typeof data === 'object') {
let convertRes = '';
for (let key in data) {
convertRes += key + '=' + data[key] + '&';
}
convertRes = convertRes.substring(0, convertRes.length - 1); //去除最后一个&
return convertRes
} else {
return data
}
}
}
ajax({
type: 'post',
url: "ajax.php",
dataType: 'json',
data: {
name: '张三',
age: 13
},
beforeSend() {
},
success(data) {
console.log(data)
},
error() {
console.log('error')
}
})