//XMLHttpRequest.UNSENT
//XMLHttpRequest.OPENED
//XMLHttpRequest.HEADERS_RECEIVED
//XMLHttpRequest.LOADING
//XMLHttpRequest.DONE
let xhr
if (window.XMLHttpRequest) {
// Mozilla, Safari...
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) {
// IE
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP')
} catch (e) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
} catch (e) {}
}
}
if (xhr) {
xhr.onreadystatechange = function onReadyStateChange() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('执行成功')
} else {
console.log('执行出错')
}
}
xhr.open('POST', '/api', true)
// 以表单的形式传递数据
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send('username=admin&password=root')
}
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: dataType,
success: function () {},
error: function () {}
});
$.get(url,function(){}); //get请求
$.post(url,body,function(){}); //post请求
$.getJSON(url,function(){}); //get请求从服务器加载Json编码
fetch(url).then(function(res) {
return res.json()
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log("Oops, error")
})
npm install fetch-jsonp --save-dev
fetchJsonp(url, {
timeout: 3000,
jsonpCallback: 'callback'
}).then(function(res) {
console.log(res.json());
}).catch(function(e) {
console.log(e)
});
npm install axios
//cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios({
method: 'GET',
url: url,
})
.then(res => {console.log(res)})
.catch(err => {console.log(err)})
// get请求
axios.get(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// post请求
axios.post(‘/user’, {
name: 'Jerry',
lastName: 'Meng'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// ajax
$.ajax({
url: '',
data: '',
success: function (data) {
$.ajax({
url: '',
data: '',
success: function (data) {
$.ajax({
...
})
}
})
}
})
//axios
axios
.get(url)
.then((res) => {
return axios.get(url)
})
.then((res) => {
//如此一层层嵌套
})
//axios
function getInfo() {
return axios.get(url)
}
function getUser() {
return axios.get(url)
}
axios.all([getInfo(), getUser()])
.then(axios.spread(function (info, user) {
// 两个请求现在都执行完成
}))