原生AJAX
const xhr =new XMLHttpRequest();
// 请求方式 路径 是否异步,默认true
xhr.open( "GET", "http://musicapi.leanapp.cn/search?keywords=天空之城", true );
xhr.send("") // 发送的内容
//请求头
xhr.setRequestHeader( "Content-type","application/json; charset=utf-8" );
xhr.onreadystatechange = function () {
if ( xhr.readyState === 4 && xhr.status >= 200 && xhr.status<300 || xhr.status ) {
console.log(xhr.responseText); //返回的内容
}
};
post
const xhr =new XMLHttpRequest();
// 请求方式 路径 是否异步,默认true
xhr.open("POST","http://musicapi.leanapp.cn/search?",true);
// method url boolean
xhr.setRequestHeader ("Content-type", "application/x-www-from-urlencoded" );
xhr.send("keywords=天空之城") // 发送的内容
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status<300 || xhr.status) {
console.log(xhr.responseText);
}
};
jquery
jQuery Ajax 常用方法有三个:get、post、ajax:
$.ajax({ // 默认是GET请求
"url": "http://musicapi.leanapp.cn/search",
"data": {
"keywords": "天空之城"
},
"dataType": "json", // 其实是jQuery帮你调用了JSON.parse()
"success": function(data) {
console.log(data);
}
});
POST 请求
$.post({
"type": "post", //请求方式
"url": "http://musicapi.leanapp.cn/search", //请求地址
"data": { //发送的参数
"keywords": "天空之城"
},
"dataType": "json", // 其实是jQuery帮你调用了JSON.parse() //返回数据格式
"success": function(data) { //返回的数据
console.log(data);
}
});
GET 请求
$.get({
"type": "get", //请求方式
"url": "http://musicapi.leanapp.cn/search",, //请求地址
"data": { //发送的参数
"keywords": "天空之城"
},
"dataType": "json", // 其实是jQuery帮你调用了JSON.parse() 返回数据格式
"success": function(data) { //返回的数据
console.log(data);
}
});
fetch
fetch("http://musicapi.leanapp.cn/search?keywords=天空之城",{
method:"GET" //请求方式
// body: JSON.stringify({ keywords: "天空之城"})
})
.then (response => response.json())
.then (data => console. log(data))
.catch(e => console. log ("Oops, error", e)); //错误捕获
POST
fetch("http://musicapi.leanapp.cn/search",{
method:"POST",
body: new URLSearchParams( [ [ "keywords", "天空之城" ] ] ).toString(), // 这里是请求对象
headers: new Headers({}), //请求头
})
.then (response => response.json()) //格式化数据
.then (data => console. log(data))
.catch(e => console. log ("Oops, error", e));
axios
GET
axios({
url: 'http://musicapi.leanapp.cn/search?keywords=天空之城"',
method: 'get',//默认就是get请求
})
.then( res => console.log( res ))
.catch( error => conosle.log( error ))
POAT
axios({
url: 'http://musicapi.leanapp.cn/search',
method: "POST",
headers: { }, //请求头
params: {
keywords: "天空之城",
}
})