Ajax是什么
Ajax为异步JavaScript和XML(Asynchronous JavaScript And XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
原生Ajax
//创建XMLHttpRequest对象。
let xhr = new XMLHttpRequest();
//打开链接 method为请求方式(get/post) url为请求地址
xhr.open(method,url);
//设置请求头信息(get请求可不设置)
xhr.setRequestHeader('Content-type','application/json');
//发送请求 data的类型和Content-type相关 applecation/json text/aplin...
//get请求data可不写 post请求取决于Content-type
xhr.send(data);
//监听响应
xhr.onreadystatechange = function(){
if(this.readyState==4){
if(this.status==200){
}
}
}
jQuery封装的Ajax
- Ajax属于jQuery的一部分 回调函数机制
- 依赖于XMLHttpRequest 自动转换data数据为字符串。
jquery封装了四个方法 $.ajax() $.get() $.post() $.load()
$.ajax({
method:'GET', //请求类型 GET /POST
url:'http://localhost:3000/user', //请求地址
headers:{
//向服务器发送内容的类型 默认为 application/x-www-form-urlencoded
"Content-type":"application/json"
},
dataType:'JSON', //预期服务器响应类型
async:true, //是否为异步请求 默认值为true false为同步请求
timeout:'3000', //本地请求超时时间
cache:true, //设置浏览器是否缓存请求的页面
success:function(res){
//请求成功执行的函数 res 服务器返回的数据 status服务器返回的状态
if(res.status==200){
}
},
//请求失败的回调函数
error:function(err){
}
})
post方法 传递表单数据
let qs = Qs;
//qs.stringify()将对象转换为字符串,属性间使用&连接,即序列化
//qs.parse()字符串转对象,反序列化
$.ajax({
//请求地址
url:'http://localhost:3000/user',
//请求方式
method:'POST',
//传递的参数
data:qs.stringify({id:1,name:'zhangsan'}),
headers:{
"Content-type":"application/x-www-form-urlencoded"
},
success:function(res){
if(res.status == 200){
//....
}
},
error:function(err){
}
})
axios
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
// 在js代码内发axios 下载依赖 引用使用
const axios = require('axios');
//axios.get('http://localhost:3000/user',{id:101})
axios.get('htpp://localhost:3000/user').then(res=>{
console.log(res);
//.....
})
.catch(err=>{
})