原生ajax
get请求
const xhr = new XMLHttpRequest();
xhr.open("GET","http://localhost:8080/server?id=1");
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >=200 && xhr.status < 300){
console.log(xhr.status)
console.log(xhr.statusText)
console.log(xhr.getAllResponseHeaders)
console.log(xhr.response)
}
}
}
post请求
const btn = document.getElementsByTagName("button")[0];
btn.addEventListener("click",function(){
const xml = new XMLHttpRequest()
xml.open("post","http://localhost:8080/server")
xml.setRequestHeader("content-type","application/x-www-form-urlencoded")
xml.send("a=1&b=2")
xml.onreadystatechange = function(){
if(xml.status >= 200 && xml.status < 300 && xml.readyState === 4){
console.log(xml.responseText)
}
}
})
处理json格式数据
const btn = document.getElementsByTagName("button")[0];
btn.onclick = function(){
const xhr = new XMLHttpRequest();
xhr.open("GET","http://localhost:8080/json-server");
xhr.responseType = "json"
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.status >=200 && xhr.status < 300 && xhr.readyState === 4){
console.log(xhr.response)
}
}
}
其他参数
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/timeout");
xhr.send();
xhr.timeout = 2000
xhr.ontimeout = function () {
console.log("超时啦")
}
xhr.onerror = function () {
console.log("网络出错了")
}
xhr.onreadystatechange = function () {
if (xhr.status >= 200 && xhr.status < 300 && xhr.readyState === 4) {
console.log(xhr.response)
}
}
xhr.abort()
其他方式使用ajax
jquery
$.get("http://localhost:8080/jquery-timeout", { name: 'chen' }, (data) => {
console.log(data)
})
$.post("http://localhost:8080/jquery-timeout", { name: 'chen' }, (data) => {
console.log(data)
}, 'json')
})
$.ajax({
url: "http://localhost:8080/jquery-timeout",
data: { a: 100, b: 200 },
type: "get",
dataType: "json",
timeout: 2000,
success: (data) => {
console.log(data)
},
err: () => {
console.log("出错了")
},
headers: {
c: 300,
d: 400
}
})
axios
axios.get('/jquery-timeout', {
params: {
a: 100,
b: 200
},
headers: {
name: 12,
age: 20
}
}).then(res => {
console.log(res)
})
axios.post('/jquery-timeout', { username: 'admin', password: 'root' }, {
params: {
a: 100,
b: 200
},
headers: {
name: 12,
age: 20
}
})
axios({
method: "post",
url: "/jquery-timeout",
params: {
a: 100,
b: 200
},
headers: {
c: 300,
d: 400
},
data: {
username: 'admin',
password: 'root'
}
}).then(res => {
console.log(res)
})
fetch
fetch("http://localhost:8080/jquery-timeout?vip=7", {
method: "post",
headers: {
a: 100,
b: 200
},
body: "username=admin&password=root"
}).then(res => {
console.log(res)
})