介绍Ajax:
- Ajax全称:Async JavaScript and Xml (异步JavaScript和XML)
- 是一种交互式网页应用的开发技术,不加载页面的情况下,与服务器实现交互数据
- 简单的来说通过XmlHttprequest对象向服务器发送异步请求,获取数据后。使用JavaScript操作dom元来刷新页面
创建:
-
创建 ajax 对象以后,我们就使⽤ ajax 对象的⽅法去发送请求和接受响应
1.创建实例
// 创建实例化 xhr异步对象
const xhr = new XMLHttpRequest()
通过xhr我们就可以发送ajax请求了
配置属性:
- xhr.status :服务器的HTTP状态码 如(404 : 未找到文件 , 200: 成功)
- ~.responseText: 服务器响应 返回的数据
- ~.statusText: 服务器返回的状态文本信息
- ~.onreadyStateChange : 事件监听服务端与你的通信状态
他是监听 readyState 的状态,只要readyState 发生变化就会触发这个事件
一般我们会监听 readyState 是不是===4 因为===4 代表成功
- ~.readyState : 请求的状态,有四个状态
0 : xhr被创建 但是没被调用open()方法
1:open()方法被调用,建立连接,
2:send()方法被调用,并且已经可以获取状态码和响应头
3:响应体下载中 responseText 属性已包含部分数据
4:完成 可以使用responseText
2.建立连接
open ⽅法有三个参数
第⼀个 请求⽅式
第⼆个 url 地址
第三个 是本次请求是否异步,默认为true 表示异步,false 同步
xhr.open('⽅式', '地址', 是否异步)
3.发送请求
//发送请求
xhr.send()
4.onreadyStateChange 监听通信状态
xhr.onreadystatechange = function () {
//是否发送成功,
if (xhr.readyState == 4) {
//200代表后台响应成功 成功之后我们就可以通过responseText拿取数据
if (xhr.status == 200) {
console.log(xhr.responseText)
}
//如果没有成功,就获取错误状态码
else {
console.log(xhr.status);
}
}
}
5.发送请求时携带参数
5.1, get与post的区别
- get参数会在url地址显示,post不会
- get相比post更快,更稳定
- post可以向服务器发送大量数据,没有数据限制
5.2,get传参 直接在url后面进行拼接
const xhr = new XMLHttpRequest()
// 直接在地址后面加一个 ?,然后以 key=value 的形式传递
// 多个数据用&分割
xhr.open('get', './wqh.text?a=100&b=200')
xhr.send()
5.3,post请求传参是携带在请求体中的
POST发送请求必须设置在 setRequestHeader 请求头
application/x-www-form-urlencoded 表单字符类型
multiline/form-data 表单类型
application/json json类型
const xhr = new XMLHttpRequest()
xhr.open('post', './wqh.text')
//Content-type设置类型
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//以key=value&key=value形式发送
xhr.send('key=value&key=value')
6,简单封装下-仿jq中$.ajax
/*
type 请求方式
url 请求url路径
data 要发送的数据
success 成功以后执行的函数
error 失败以后执行的函数
.toLowerCase()将字符串转换成小写 对其他类型不影响
*/
function $ajax({
type = "get",
url,
data,
success,
error
}) {
//当type不传值的时候给他默认值get
xhr = new XMLHttpRequest(); // 实例化xhr对象
/**
* 如果请求方式为get 并且data参数存在的话
* 我们就要和地址进行拼接 因为get传参方式是在url后边拼接
* 我们要对他进行处理
**/
if (type.toLowerCase() == "get" && data) {
url += "?" + querystring(data);
}
xhr.open(type, url, true);
if (type.toLowerCase() == "get") {
xhr.send();
} else {
//设置提交数据格式 :content-type
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
//如果data有数据的话 我们就在将参数放到send中 没有的话就直接请求
data ? xhr.send(querystring(data)) : xhr.send();
}
//监听通信
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (success) {
success(xhr.responseText); //将接收的数据抛出
}
} else {
if (error) {
error("Error:" + xhr.status); //将错误的状态码抛出
}
}
}
}
}
function querystring(obj) { //querystring函数就是对我们接收data对象进行处理
var str = '';
for (var attr in obj) { //首先循环obj这个对像
str += attr + "=" + obj[attr] + "&"; //拿到里边的 键值 以 = 号进行拼接 在末尾加上 &
}
return str.substring(0, str.length - 1); //这一步是因为拼接完成的str 末尾会有一个&
}
window.onload = function () {
var aBtns = document.getElementsByTagName("button");
aBtns[0].onclick = function () {
$ajax({
url: "abc.txt",
data: {
username: "老六",
age: 66,
password: "sixsix"
},
success: function (result) {
alert("GET请求到的数据:" + result);
},
error: function (msg) {
alert("GET请求数据错误:" + msg);
}
})
}
aBtns[1].onclick = function () {
$ajax({
type: "post",
url: "http://localhost:3000/data",
// data: {
// username: "小王",
// age: 18,
// password: "200202"
// },
success: function (result) {
alert("POST请求到的数据:" + result);
},
error: function (msg) {
alert("POST请求数据错误:" + msg);
}
})
}
}