Ajax学习笔记,第一节:语法基础
一、概念
1、什么是Ajax
使用浏览器的 XMLHttpRequest 对象 与服务器通信
2、什么是axios
Axios是一个基于Promise的JavaScript库,支持在浏览器和Node.js环境中使用。相较于Ajax,Axios提供了更多的功能,如拦截请求和响应、转换请求和响应数据、取消请求等,
这使得开发者能够更方便地处理和管理HTTP请求。Axios相较于Ajax兼容性更好,支持现代浏览器,而Ajax在一些旧版本浏览器中可能会出现一些兼容性问题。在安全性方面,Axios支持防御XSRF(跨站请求伪造),而Ajax本身并不直接支持这一防御机制。
3、认识URL
·URL的组成:协议,域名,资源路径
(URL 组成有很多部分,我们先掌握这3个重要的部分即可)
·http协议,超文本传输协议。规定了浏览器和服务器传递数据的格式·域名,标记服务器在互联网当中的方位,网络中有很多服务器,你想访问哪一台,就需要知道它的域名。·资源路径,一个服务器内有多个资源,用于标识你要访问的资源具体的位置
4、准备
https://www.apifox.cn/apidoc/project-1937884
这里 有 现成的后端服务,我们在练习时直接使用即可
二、Axios使用
1、初步使用
1> 引入 axios.js 文件到自己的网页中https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js2> 语法:axios({url: '请求路径',method: '请求方法',data:{参数名:值}}).then((res)=>{//对服务器返回的数据做处理});
< body> < h3> 1、省份列表</ h3> < p class = " my-provs" > </ p> < h3> 新闻列表</ h3> < p class = " my-news" > </ p> < script src = " https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js" > </ script> < script> axios ( { url: "https://hmajax.itheima.net/api/province" } ) . then ( ( res ) => { console. log ( res) ; if ( res != undefined ) { let provList = res. data. list; document. querySelector ( ".my-provs" ) . innerHTML = provList. join ( "<br>" ) ; } } ) ; axios ( { url: "https://hmajax.itheima.net/api/news" } ) . then ( ( res ) => { console. log ( res) ; if ( res != undefined ) { let newsList = res. data. data; let newsInnerHtml = "" ; newsList. forEach ( ele => { newsInnerHtml = newsInnerHtml + " <a>" + ele. title + "</a><br><img src=" + ele. img + "><br/> " ; } ) ; console. log ( newsInnerHtml) ; document. querySelector ( ".my-news" ) . innerHTML = newsInnerHtml; } } ) </ script>
</ body>
2、携带查询参数
语法:
axios({url:"请求路径",params:{//查询参数 params 或在URL后拼接成?xxx=yyy&ooo=ddd格式}
}).then((res)=>{//结果处理
});//注意:
参数中 当属性名和value位置变量名同名即可简写
< body> < h3> 城市列表:</ h3> < input type = " text" name = " cityname" > < input type = " button" class = " slt-btn" value = " 点我" > < p class = " my-city" > </ p> < script src = " https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js" > </ script> < script> let cliBtn = document. querySelector ( ".slt-btn" ) ; cliBtn. addEventListener ( 'click' , ( ) => { let inputVal = document. querySelector ( "input[name='cityname']" ) ; axios ( { url: "https://hmajax.itheima.net/api/city" , params: { "pname" : inputVal. value} } ) . then ( res => { console. log ( res) ; if ( res != undefined ) { let cityList = res. data. list; document. querySelector ( ".my-city" ) . innerHTML = cityList. join ( "<br/>" ) ; } } ) } ) ; </ script>
</ body>
3、常用请求方法和数据提交
请求方法是一些固定单词的英文,例如:GET,POST,PUT,DELETE,PATCH
(这些都是http协议规定的),每个单词对应一种对服务器资源要执行的操作axios内部设置了默认请求方法就是GET
请求方法 操作 GET 获取数据 POST 数据提交 PUT 修改数据(全部) DELETE 删除数据 PATCH 修改数据(部分)
#语法:
axios({url: '目标资源地址',method: '请求方法',data: { //注意这里是data 而不是 params参数名: 值}
}).then(result => {// 对服务器返回的数据做后续处理
})
< body> < label for = " un" > 用户名:</ label> < input type = " text" name = " username" id = " un" > < label for = " pwd" > 密码:</ label> < input type = " password" name = " password" id = " pwd" > < input type = " button" value = " 注册" class = " btn" > < script src = " https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js" > </ script> < script> let submitBtn = document. querySelector ( ".btn" ) ; submitBtn. addEventListener ( 'click' , ( ) => { let username = document. querySelector ( "#un" ) . value; let password = document. querySelector ( "#pwd" ) . value; if ( username != undefined && password != undefined ) { axios ( { url: "https://hmajax.itheima.net/api/register" , method: 'POST' , data: { username, password} } ) . then ( res => { console. log ( res. data) ; if ( res. data == undefined ) { alert ( "注册失败" ) ; return ; } if ( res. data. code == '10000' ) { alert ( "账号注册成功" ) ; } else { alert ( res. data. message) ; } } ) ; } else { alert ( "请输入用户名和密码" ) ; } } ) ; </ script>
</ body>
4、Axios错误处理
##语法:
axios({// ...请求选项
}).then(result => {// 处理成功数据
}).catch(error => {// 处理失败错误
})
< script> let submitBtn = document. querySelector ( ".btn" ) ; submitBtn. addEventListener ( 'click' , ( ) => { let username = document. querySelector ( "#un" ) . value; let password = document. querySelector ( "#pwd" ) . value; if ( username != undefined && password != undefined ) { axios ( { url: "https://hmajax.itheima.net/api/register" , method: 'POST' , data: { username, password} } ) . then ( res => { console. log ( res. data) ; if ( res. data == undefined ) { alert ( "注册失败" ) ; return ; } if ( res. data. code == '10000' ) { alert ( "账号注册成功" ) ; } else { alert ( res. data. message) ; } } ) . catch ( error => { console. log ( error. message) ; console. log ( error. response. data) ; console. log ( error. response. data. message) ; alert ( error. response. data. message) ; } ) ; } else { alert ( "请输入用户名和密码" ) ; } } ) ; < / script>
5、form-serialize插件
我们前面收集表单元素的值,是一个个标签获取的
如果一套表单里有很多很多表单元素,如何一次性快速收集出来呢.
使用 form-serialize 插件提供的 serialize 函数就可以办到语法:
serialize(参数1,参数2)参数1:要获取的form表单标签对象,要求表单元素需要有name属性,用来作为收集的数据中属性名
参数2:配置对象hash:true==>收集出来是一个JS对象结构false==>收集出来是一个查询对象格式empty:true==>收集空值false==>不收集空值
< body> < form action = " javascript:;" class = " my-form" > < input type = " text" name = " username" > < br> < input type = " text" name = " password" > < br> < input type = " button" class = " btn" value = " 提交" > </ form> < script src = " ./js/form-serialize.js" > </ script> < script src = " https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js" > </ script> < script> let btn = document. querySelector ( ".btn" ) ; btn. addEventListener ( 'click' , ( ) => { let myForm = document. querySelector ( ".my-form" ) ; const data = serialize ( myForm, { hash: true , empty: false } ) ; const { username, password } = data; axios ( { url: "https://hmajax.itheima.net/api/login" , method: "POST" , data: { username, password} } ) . then ( res => { alert ( res. data. message) ; } ) } ) </ script>
</ body>
三、Ajax原理解析
1、XMLHttpRequest 简单请求
·AJAX 是浏览器与服务器通信的技术,采用 XMLHttpRequest 对象相关代码
·axios 是对 XHR 相关代码进行了封装,让我们只关心传递的接口参数#语法:
const xhr = new XMLHttpRequest()
xhr.open('请求方法', '请求url网址')
xhr.addEventListener('loadend', () => {// 响应结果console.log(xhr.response)
})
xhr.send()
< h3> 省份</ h3>
< p class = " my_prov" > </ p>
< script> const xhr = new XMLHttpRequest ( ) ; xhr. open ( "GET" , "http://hmajax.itheima.net/api/province" ) ; xhr. addEventListener ( "loadend" , ( ) => { console. log ( xhr. response) ; let res = JSON . parse ( xhr. response) ; console. log ( res) ; const my_prov = document. querySelector ( ".my_prov" ) ; my_prov. innerHTML = res. list. join ( "<br>" ) } ) ; xhr. send ( ) ;
</ script>
##拓展:
进度事件的种类:
进度事件用来描述资源加载的进度,主要由 AJAX 请求< img> 、< audio> 、< video> 、< style> 、< link>
等外部资源的加载触发,继承了ProgressEvent接口。它主要包含以下几种事件。·abort:外部资源中止加载时(比如用户取消)触发。如果发生错误导致中止,不会触发该事件。
·error:由于错误导致外部资源无法加载时触发。
·load:外部资源加载成功时触发。
·loadstart:外部资源开始加载时触发。
·loadend:外部资源停止加载时触发,发生顺序排在error、abort、load等事件的后面。
·progress:外部资源加载过程中不断触发。
·timeout:加载超时时触发。
2、XMLHttpRequest 请求参数(简单参数)
#实现::http://xxxx.com/xxx/xxx?参数名1=值1&参数名2=值2
const xhr2 = new XMLHttpRequest();
xhr2.open("GET", "http://hmajax.itheima.net/api/city?pname=河北省");
//1-3、监听回调
xhr2.addEventListener("loadend", () => {console.log(xhr2.response);//JSON解析let res = JSON.parse(xhr2.response);console.log(res);const my_city = document.querySelector(".my_city");my_city.innerHTML = res.list.join("< br> ")
});//监听loadend事件
//1-4、发送请求
xhr2.send();//发送请求
3、XMLHttpRequest 请求参数(多个)
##语法
let queryParams = new URLSearchParams({"pname": "河北省","cname": "邯郸市"
});
let queryString = queryParams.toStrng();
const xhr3 = new XMLHttpRequest ( ) ; let queryParams = new URLSearchParams ( { "pname" : "河北省" , "cname" : "邯郸市" } ) ; xhr3. open ( "GET" , "https://hmajax.itheima.net/api/area?" + queryParams. toString ( ) ) ; xhr3. addEventListener ( "loadend" , ( ) => { console. log ( xhr3. response) ; let res = JSON . parse ( xhr3. response) ; console. log ( res) ; const my_area = document. querySelector ( ".my_area" ) ; my_area. innerHTML = res. list. join ( "<br>" ) } ) ; xhr3. send ( ) ;
4、XMLHttpRequest数据提交
##语法:
xhr4.setRequestHeader("Content-Type", "application/json");
let data = { "username": username, "password": password };
let dataStr = JSON.stringify(data);
xhr4.send(dataStr);
const registBtn = document. querySelector ( ".btn" ) ;
registBtn. addEventListener ( "click" , function ( ) { let username = document. querySelector ( "#un" ) . value; let password = document. querySelector ( "#pwd" ) . value; if ( username == undefined || password == undefined ) { alert ( "请输入用户名和密码" ) ; return ; } const xhr4 = new XMLHttpRequest ( ) ; xhr4. open ( "POST" , "https://hmajax.itheima.net/api/register" ) ; xhr4. addEventListener ( "loadend" , ( ) => { console. log ( xhr4. response) ; let res = JSON . parse ( xhr4. response) ; if ( res != undefined && res. code != '10000' ) { alert ( res. message) ; } else { alert ( "账号注册成功.id为:" + res. data. id) ; } } ) xhr4. setRequestHeader ( "Content-Type" , "application/json" ) ; let data = { "username" : username, "password" : password } ; let dataStr = JSON . stringify ( data) ; xhr4. send ( dataStr) ;
} ) ;