常用的发送Ajax请求的方式有三种:
1.$Ajax
jQuery封装的,不推荐的(jQuery本身操作原生dom);
$.ajax({
type: "GET",//请求类型:GET POST 其他请求方式eg:PUT DELETE(仅部分浏览器支持)
url: "/select",//ajax请求地址
dataType:'json',//预期服务器返回的数据类型
data: {id:001},//传递的参数
success: function(data){
console.log("返回的数据: " + data );
}
});
2.原生js fetch
:封装了两层promise,返回的数据要通过调用两次.then获取,兼容性不好,ie不支持
fetch("/some/url", {
method: "post",
headers: {name: "lilei"},//对应的 Headers 对象
//请求参数
body: JSON.stringify({
email: 'huang@163.com'
name: 'jim'
})
}).then(function (r) {
return r.text();/ 第一个then 设置请求的格式
}).then((r) => {
console.log(r);/ 第二个then 处理回调
})
3.axios
推荐,体积小,通过promise封装,使用方便
//原始的Axios请求方式
axios({
method: 'post',//请求方式
url: 'http:127.0.0.1:5000/user/12345',//请求的接口
data: {//请求传递的数据
firstName: 'Fred',
lastName: 'Flintstone'
},
...//其他相关配置
}).then(res=>{
console.log(res)//请求成功的结果
}).catch(error=>{
console.log(error)//请求失败的结果
});