原生Ajax,jQuery封装Ajax以及axios

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=>{
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新猿忆码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值