XMLHttpRequest基本使用
1.XMLHttpRequest(简称xhr)是浏览器提供的 JavaScript对象,通过他它,可以请求服务器上的数据资源 。之前所学的jQuery中的Ajax函数,就是基于xhr对象封装出来了的
2.用xhr发起get请求
-
创建xhr对象
-
调用xhr. open()函数
-
调用xhr. send()函数
-
监听xhr.onreadystatechange事件
3.使用xhr发起post请求
-
创建xhr对象
-
调用xhr. open()函数
-
设置Content-Type属性(固定写法)
-
调用xhr.send()函数,同时指定要发送的数据
-
监听xhr.onreadystatechange事件
XMLHttpRequest - 基础使用
-
AJAX 是浏览器与服务器通信的技术,采用 XMLHttpRequest 对象相关代码
-
axios 是对 XHR 相关代码进行了封装,让我们只关心传递的接口参数
-
学习 XHR 也是了解 axios 内部与服务器交互过程的真正原理
语法:
案例:获取所有省份列表并展示到页面上
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>
</p>
<script>
// 1.创建xhr对象
const xhr=new XMLHttpRequest()
// 2.设置请求方法,请求url
xhr.open('get','http://hmajax.itheima.net/api/province')
// 3.监听loadend事件,接收响应结果
xhr.addEventListener('loadend',()=>{
// 将返回的json结果转化成js数组
const res=JSON.parse(xhr.response)
console.log(res)
// 插入p标签,在数组每个元素后加入<br>
document.querySelector('p').innerHTML=res.list.join('<br>')
})
//4.调用方法
xhr.send()
</script>
</body>
</html>
XMLHttpRequest数据提交
<body>
<button class="reg-btn">注册用户</button>
<script>
/**
* 目标:使用xhr进行数据提交-完成注册功能
* POST http://hmajax.itheima.net/api/register
* Body 参数(application/json)
* username
* password
*/
document.querySelector('.reg-btn').addEventListener('click', () => {
// 1. 创建 xhr 对象
const xhr = new XMLHttpRequest()
// 2. 设置请求方法和 url
xhr.open('post', 'http://hmajax.itheima.net/api/register')
// 3. 监听 loadend 事件获取响应
xhr.addEventListener('loadend', () => {
const res = JSON.parse(xhr.response)
console.log(res)
})
// 4. 设置请求头
// 参数1: 键
// 参数2: 值
xhr.setRequestHeader('Content-Type', 'application/json')
// 5. 发请求 -> 携带参数
const user = {
username: 'mrdrager123',
password: '123456'
}
//将数据转化为json格式
xhr.send(JSON.stringify(user))
})
</script>
</body>
URL编码与解码
1.什么是url编码
URL地址中只允许出现英文相关的字母、标点符号、数字 , 因此,在url地址中不允许出现中文字符 。如果url中需要包含中文这样的字符 ,这必须对中文字符进行编码 (转义)
Url编码的原则:使用英文字符去表示非英文字符
2.如何对url进行编码与解码
浏览器提供了url编码与解码的API ,分别是 :
encodeURI()编码的函数 decodeURI()解码的函数