1.发送请求的步骤
/*get 和 post 实战用法的区别
1、get 会把参数放在url上显示 所以不安全
2、post 不会把参数显示到url上 登录的时候推荐使用psot
3、get 传输的数据有限制 2kb 只支持 ASCII 字符
4、post 传输没有大小限制,没有限制,也允许二进制数据传输文件或者图片的时候使用 post请求
*/
//1.创建xhr请求对象
let xhr = new XMLHttpRequest()
//2.配置请求信息
/* open(方法,文件名,同步异步)
参数一:post/get
参数二:请求的文件路径
参数三:同步(false) 异步(true) */
xhr.open('post', 'http://www.liulongbin.top:3006/api/addbook')
// ☠ POST请求头进行的配置 —— Content-type :请求文件格式
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
/*
3.发送请求
Post在send()时传递键值对
Get在路径后拼接键值对
*/
xhr.send('bookname=嘎嘎x&author=xx&publisher=xxx出版')
/*
4.监听请求状态 => 获取返回值
onreadystatechange监听请求状态
*/
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let toJsObj = JSON.parse(xhr.responseText)
console.log(toJsObj)
}
}
请求状态码
function ajaxFn() {
let xhr = new XMLHttpRequest();
/* 0: 请求未初始化,XMLHttpRequest对象已经创建,但还没有调用open()方法/创建请求 */
console.log('请求未初始化',xhr.readyState)
xhr.open('get', 'abc.txt', true)
xhr.send();
/* 1: 已经调用open() 方法,请求已建立,但尚未发送请求 */
console.log('服务器连接已建立',xhr.readyState)
/* onreadystatechange就是用来监听readyState值的变化的 */
xhr.onreadystatechange = function () {
/* 2: 请求已发送,正在处理中(通常现在可以从响应中获取内容头) */
if(xhr.readyState == 2){
console.log('请求已接收',xhr.readyState)
}
/* 3: 请求在处理中;通常响应中已有部分数据可用了,但是服务器还没完成响应的生成 */
if(xhr.readyState == 3){
console.log('请求处理中',xhr.readyState)
}
/* 4: 响应完成,已经接收到了全部数据,并且连接已经关闭。*/
if(xhr.readyState == 4){
console.log('请求已完成',xhr.readyState)
}
/* xhr.responseText 通过ajax请求获得的数据 */
// console.log(xhr.responseText)
console.log('响应状态码',xhr.status);
}
}
封装 Ajax
/* 1.将用户信息转换成查询字符串格式
let obj = { name: 'xx', age: 11 } => 'name=xx&age=11'
*/
function toStr (data) {
let arr = []
//遍历属性进行格式拼接
for (let key in data) {
let str = key + '=' + data[key]
// 将每一条数据存到数组
arr.push(str)
}
//将数组转换为字符串且修改连接符为&
return arr.join('&')
}
/* 2.主体封装 */
function ajax (options) {
let xhr = new XMLHttpRequest()
// 2.1 判断请求方式
if (options.method.toUpperCase() === 'GET') {
// get:查询参数在url后拼接
xhr.open('get', options.url + '?' + toStr(options.data))
}
else if (options.method.toUpperCase() === 'POST') {
// post需配置请求头;查询参数在send()时发送
xhr.open('post', options.url)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(toStr(options.data))
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 将响应Json数据转换为js对象
let res = JSON.parse(xhr.responseText)
options.success(res)
}
}
}
Json数据
格式

<script>
/*
json格式:(json为字符串需 ''包裹)
1.对象格式-'{"key":value}'
key和字符串类型的value用"包裹"
2.数组格式-'["value","value"]'
json数据value类型:
数字、字符串、布偶、数组、对象、null
*/
let json = '{"name": "ws", "age": 21 }'
let json2 = '[[1,2,3],"ws"]'
// json=>js对象
let toJs = JSON.parse(json)
let toJs2 = JSON.parse(json2)
console.log(toJs)
console.log(toJs2)
// js对象=>json
let toJson = JSON.stringify(toJs)
console.log(toJson);
</script>