- 前端的数据传输基本是依靠ajax来向服务端发起请求获得数据的
请求方式最常用的有两种
- GET (一般用于获取数据)
- POST (提交数据 敏感 修改 新增 数据)
这二者是有区别的, 具体的可以看我往期的文章
然后今天就分享一下用原生js 写ajax的请求
- 示例一(GET 和 POST请求 单独发起示例):
//ajax GEt请求实现步骤
function myAjaxGet() {
let xhr
//兼容判断
if (window.XMLHttpRequest) {//AJAX - 创建 XMLHttpRequest 对象,需要判断浏览器的兼容
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) {
// 兼容低版本 IE
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
//事件处理,通过该事件来判断请求是否成功
/**
* readyState值
* 0:未初始化,就是没有调用open();
* 1启动,已经调用open(),但是没有调用send();
* 2发送,调用send(),但是没有收到响应
* 3:接收,响应体还没有接收完成;
* 4:完成,接收到全部的响应数据。
*
*/
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) {//详见上方readyState值介绍
return//请求完成直接返回
}
if (xhr.status == 200) {
console.log(xhr.responseText)
} else {
console.log("请求失败", xhr)
}
}
//请求配置
//get请求的参数必须放在url上,以?开头,例如 ?key=value&key=value
xhr.open("get", "/user/list?id=1", true) //true是异步 false是同步
//发送
xhr.send(null)
}
//ajax POST请求实现步骤
function myAjaxPost() {
// ajax 实现步骤
let xhr
// 兼容判断
if (window.XMLHttpRequest) {//AJAX - 创建 XMLHttpRequest 对象,需要判断浏览器的兼容
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) {
// 低版本 IE
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
// 事件处理,通过该事件来判断请求成功与否
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) {//上面提到过的 4:完成,接收到全部的响应数据。
return
}
if (xhr.status == 200) {
console.log(xhr.responseText)
} else {
console.log("请求失败:", xhr)
}
}
//请求配置
//区别!! post请求url这里可以不写参数的
xhr.open("POST", "/users/list", true)
// 在 open 之后,send 之前,必须设置请求头
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// 发送请求
// POST 在这里提交数据
xhr.send("id=1&username=jack")
}
- 示例二(GET 和 POST请求 单独发起示例):
//封装在一起传参使用
function myAjax(method, url, data) {
//method 代表请求方式 post get .等
//url 代表请求地址
//data 代表发送的数据
let xhr
//兼容判断(固定写法)
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) {
// 低版本 IE
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
//事件处理,通过该事件来判断请求是否成功(固定写法)
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) {
return
}
if (xhr.status == 200) {
console.log(xhr.responseText)
} else {
console.log("请求失败", xhr)
}
}
//判断请求类型
if(method == "GET"){
// GET 请求参数放在 url (地址)上面,以 ? 开头(数据),多个参数通过 & 连接
xhr.open(method, url + "?" + data, true)
xhr.send(null)
}else if(method == "POST"){
//请求配置
//POST请求url这里可以不写参数
xhr.open(method, url, true)
// 在 open 之后,send 之前,必须设置请求头
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// 发送请求
// POST 在这里提交数据
xhr.send(data)
}
}
//调用语句
btn.onclick = function () {
myAjax({
method: 'POST',
url: '/users/list',
data: {
id: "1",
username: "jack"
}
})
.then(res =>{
console.log(res)
if(res.code == 200){
alert(res.msg)
}else{
alert('获取数据失败')
}
})
.catch(err => {
console.log('失败: ', err)
})
}
- 示例三(用promise 封装AJAX)
function myAjax({
method = "GET",
url = null,
data = null,
async = true,
timeout = 3000
}) {
return new Promise((resolve,reject) => {
// ajax 实现步骤
let xhr
// 兼容判断
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) {
// 低版本 IE
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
// 事件处理,通过该事件来判断请求成功与否
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) {
return
}
if (xhr.status == 200) {
// console.log(xhr.responseText)
// 默认接收的是 字符串格式数据
resolve(JSON.parse(xhr.responseText))
} else {
// console.log("请求失败:", xhr)
reject(xhr)
}
}
// 设置请求超时
xhr.timeout = timeout // 单位是毫秒
if (method == "GET") {
// GET 请求参数放在 url 上面,以 ? 开头,多个参数通过 & 连接
xhr.open(method, url + "?" + formatData(data), async)
xhr.send(null)
} else if (method == "POST") {
// 请求配置
// POST 请求 url 这里可以不写参数的
xhr.open(method, url, async)
// 在 open 之后,send 之前,必须设置请求头
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// 发送请求
// POST 在这里提交数据
xhr.send(formatData(data))
}
})
}
// 数据处理
// data 需要 'userId=1&price=300' 这样的格式
// 期望:写的时候: {userId: 1, price: 300}
// 现在要做的是:对象 => 字符串
function formatData(data) {
// 需要保证 data 为对象
if (Object.prototype.toString.call(data) === "[object Object]") {
let arr = []
for (let key in data) {
//遍历 然后返回想要的格式数据 装入数组
arr.push(key + "=" + data[key])
}
return arr.join("&")//数组用&符号连接
}
return data
}
//模拟数据
let data = {id: 1,username:"jack"}
Nodejs中数据请求get和post的区别和理解
Nodes中Promise的理解与使用
Node.js安装及环境配置图解