1.原生ajax
var url = "http://192.168.4.18:8000/"
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
console.log(result)
}
}
2.回调函数去封装ajax
// 需要记住传参的顺序
function ajax(url,method="get",success) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
success(result)
}
}
}
function ajax({
url,
method="get",
success
}) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
success(result)
}
}
}
3. jquery-ajax
$.ajax({
url:"http://192.168.4.18:8000/",
type:"get",
dataType:"json",
success:res=>{
console.log(res)
}
})
4.callback封装jquery-ajax
function http({url,type="get",success}){
$.ajax({
url,
type,
dataType:"json",
success:res=>{
success(rs)
}
})
}