Ajax
(现在的页面基本上都有ajax的功能,就是去请求访问一些接口,获取一些数据)
手写一个XMLHttpRequest去发起请求
核心代码演示:
初始化:
Ajax.js
//访问 '/data/test.json'
//初始化实例
const xhr = new XMLHttpRequest()
/*参数:方法,请求地址,false为异步请求(为什么是异步请求,网络请求不能卡顿)
* open 未发送
*/
xhr.open('GET', '/data/test.json', true)
//当readystate变化的时候会触发函数--不send不会改变,send的时候会一直触发状态变化,readyState/status会一直变,每次变都会触发函数
xhr.onreadystatechange = function () {
//只有readyState === 4 和 status === 200,才会正常返回数据
if(xhr.readyState === 4) {
if(xhr.status === 200) {
alert(xhr.responseText)
}else{
console.log('其他情况')
}
}
}
//因为是GET请求,所以不用发送任何数据,发null即可
xhr.send(null)
效果:
//访问 '/data/test.json'
//初始化实例
const xhr = new XMLHttpRequest()
/*参数:方法,请求地址,true为异步请求(为什么是异步请求,网络请求不能卡顿)
* open 未发送
*/
xhr.open('GET', '/data/test.json', true)
//当readystate变化的时候会触发函数--不send不会改变,send的时候会一直触发状态变化,readyState/status会一直变,每次变都会触发函数
xhr.onreadystatechange = function () {
//只有readyState === 4 和 status === 200,才会正常返回数据
if(xhr.readyState === 4) {
if(xhr.status === 200) {
//通过JSON.parse()把test.json里面的数据转换为json对象
console.log(JSON.parse(xhr.responseText))
alert(xhr.responseText)
}else{
console.log('其他情况')
}
}
}
//因为是GET请求,所以不用发送任何数据,发null即可
xhr.send(null)
效果:
POST写法:(模拟)
//初始化实例
const xhr = new XMLHttpRequest()
/*参数:方法,请求地址,false为异步请求(为什么是异步请求,网络请求不能卡顿)
* open 未发送
*/
xhr.open('POST', '/login', true)
//当readystate变化的时候会触发函数--不send不会改变,send的时候会一直触发状态变化,readyState/status会一直变,每次变都会触发函数
xhr.onreadystatechange = function () {
//只有readyState === 4 和 status === 200,才会正常返回数据
if(xhr.readyState === 4) {
if(xhr.status === 200) {
alert(xhr.responseText)
}else{
console.log('其他情况')
}
}
}
const postData = {
username: ‘zhangsang’,
password: ‘xxx’
}
//因为是POST请求,发送为字符串数据
xhr.send(JSON.stringify(postData))
301:永久重定向,永远都定向到b的地址,例子:访问地址a的时候,永远都会定向到地址b
302: 临时重定向(一次的),例子:去访问a地址,返回302,就会自动跳转到b,下次再去访问a地址的时候,还是会访问a
304: 访问资源未改变,那服务器返回304,并没有返回新的资源,那浏览器就会用自身缓存的资源去用。
404: 请求地址有错误,服务端没有,找不到
403: 客户端没有权限,管理系统常用
模拟404:
没有test1.json
//初始化实例
const xhr = new XMLHttpRequest()
/*参数:方法,请求地址,false为异步请求(为什么是异步请求,网络请求不能卡顿)
* open 未发送
*/
xhr.open('GET', '/data/test1.json', true)
//当readystate变化的时候会触发函数--不send不会改变,send的时候会一直触发状态变化,readyState/status会一直变,每次变都会触发函数
xhr.onreadystatechange = function () {
//只有readyState === 4 和 status === 200,才会正常返回数据
if(xhr.readyState === 4) {
if(xhr.status === 200) {
//通过JSON.parse()把test.json里面的数据转换为json对象
// console.log(JSON.parse(xhr.responseText))
alert(xhr.responseText)
}else if(xhr.status ===404){
console.log('404 not found
}
}
}
//因为是GET请求,所以不用发送任何数据,发null即可
xhr.send(null)