1、ajax、axios总结
2018-08-10 11:21:13来源:博客园 阅读 ()
一.原生js实现ajax请求:
步骤:
get请求:
// 1.创建一个XMLHttpRequest的对象.
var xml=null; //初始值设为空
if(XMLHttpRequest){
xml=new XMLHttpRequest; //兼容非IE6
}else{
xml=new ActiveXObject('Microsoft.XMLHTTP'); //兼容IE6浏览器
}
//2.通过open与服务器建立连接 open(method,url,async) ;
//method包含 GET、POST、PUT方式。
//第三个参数同步(false)或者异步(true)
xml.open('GET',url,true);
//3.发送请求 send(string)
//string(参数) 仅用于post请求,GET请求不需要传参数,如果有参数直接拼接到url中。
xml.send();
//4.状态和响应
xml.onreadystatechange=function(){
//当readyState==4并且status==200时请求成功,否则请求失败
if(xml.readyState==4&&xml.status==200){
//请求成功
}else{
//请求失败
}
}
2.post请求:
//步骤同 get
var xml=null;
var data={a:1,b:2};
if(XMLHttpRequest){
xml=new XMLHttpRequest;
}else{
xml=new ActiveXObject('Microsoft.XMLHTTP')
}
xml.open('POST',url,true);
xml.send(data); //这里的data是要传递的参数
xml.onreadystatechange=function(){
if(xml.readyState==4&&xml.status==200){
//请求成功
}else{
//请求失败
}
}
二.jq实现ajax请求:
get请求:
// 1.get请求
$.ajax({
type:"get",
url:"",
async:true,
timeout:3000, //timeout:响应超时时间,非必须参数
beforeSend:function(){
//这里是发送请求之前所要进行的操作
},
success:function(){
//请求成功
},
error:function(){
//请求失败
}
});
post请求
$.ajax({
type:"post",
url:"",
data:{a:1,b:2},//需要传递的参数
async:true,
timeout:3000, //timeout:响应超时时间,非必须参数
beforeSend:function(){
//这里是发送请求之前所要进行的操作
},
success:function(){
//请求成功
},
error:function(){
//请求失败
}
});
三.axios请求:
首先安装axios,
方法一:npm install axios
方法二: CDN引入 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
get请求:
//1.get请求(无参数)
axios.get('http://www.xxx')
.then(function(response){
//请求成功
}).catch(function(erroe){
//请求失败
});
//2.get请求(有参数)
axios.get('http://www.xxx?a=1&b=2')
.then(function(response){
//请求成功
}).catch(function(erroe){
//请求失败
});
post请求:
//必须引入qs对data进行stringify 安装axios时已经安装了qs,无需再安装,引入即可用。
// import Qs from 'qs'
let data=Qs.stringify({a:1,b:2});
axios.post('http://www.xxx',data)
.then(function(response){
//请求成功
}).catch(function(error){
//请求失败
})
//4.多个请求同时发送
function axiosOne(){
return axios.get('http://www.url.one')
};
function axiosTwo(){
return axios.get('http://www.url.two')
};
axios.all([axiosOne(),axiosTwo()])
.then(axios.spread(function(acct, perms){
console.log(acct);//请求一的结果;
console.log(perms);//请求二的结果
}))
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- Javascript Ajax异步读取RSS文档具体实现 2020-02-25
- jquery 操作iframe的几种方法总结 2020-02-22
- 高效的jQuery代码编写技巧总结 2020-02-15
- jquery ajax检测用户名是否存在的方法 2020-02-14
- 总结js常用数组的操作方法 2019-12-13
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
