JavaScript全解析——Ajax(上)

什么是ajax

●认识前后端交互
○就是 前端 与 后端的 一种通讯方式
○主要使用的技术栈就是 ajax (async javascript and xml)
●ajax 特点
○使用 ajax 技术网页应用能够快速的将新内容呈现在用户界面
○并且不需要刷新整个页面, 也就是能够让页面有 "无刷更新" 的效果
●注意点:
○前后端交互只能交互 字符串
○并且有自己的固定步骤
创建ajax 基本步骤的是什么
1.创建 ajax 对象

const xhr = new XMLHttpRequest()

2.配置 ajax 对象

// xhr.open('请求的方式', '请求的地址', 是否异步)
xhr.open('GET', 'http://localhost:8888/test/first', true)

3.发送请求

xhr.send()

4.接收响应

xhr.onload = function () {
    console.log('请求回来了~~~~~~~~')
    console.log(xhr.responseText)
}

ajax 状态码有哪些

●简单来说其实就是用一个数字表明了当前 ajax 运行到哪一步了
●语法: xhr.readyState
○0: 创建 ajax 成功
○1: 当前 ajax 配置成功
○2: 当前 ajax 发送成功(响应已经回到浏览器了)
○3: 表示浏览器当前正在解析本次响应, 但可能还没完成
○4: 表示浏览器已经完成解析本次响应, 可以正常使用 responseText 了
●0 和 1, 比较好打印, 2/3/4 这几个我们可以借助一个 事件去打印
○readyStatechange 事件
○通过事件名其实就可以看出, 当 readyState 发生改变时就会执行

const xhr = new XMLHttpRequest()
console.log(xhr.readyState) // 0

xhr.open('GET', 'http://localhost:8888/test/first', true)
console.log(xhr.readyState) // 1

xhr.onreadystatechange = function () {
    if (xhr.readyState === 2) console.log(xhr.responseText)
    if (xhr.readyState === 3) console.log(xhr.responseText)
    if (xhr.readyState === 4) console.log(xhr.responseText)
}

xhr.send()

ajax 常见请求方式有哪些

● GET
○表示向服务器获取资源
●POST
○表示向服务器提交信息,通常用于产生新的数据,比如注册
●PUT
○表示希望修改服务器的数据, 通常用于修改某数据
●DELETE
○表示希望删除服务器的数据
●OPTIONS
○发生在跨域的预检请求中,表示客户端向服务器申请跨域提交
ajax 中 get 和 post 请求携带参数的方式
●GET: 直接拼接在请求路径后, 以 ? 间隔, 使用 key=value 的形式书写, 当有多个参数的时候用 & 连接

const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8888/test/third?name=QF666&age=18')
xhr.send()
xhr.onload = function () {
    let res = JSON.parse(xhr.responseText)
    console.log(res)
}

●POST
○在请求体内携带参数(其实就是 send 小括号内部)
○并且需要设置请求头内部的 content-type
■如果参数为 查询字符串, 需要添加:
●'xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')'
■如果参数为 JSON 字符串, 需要添加:
●'xhr.setRequestHeader('content-type', 'application/json')'

const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:8888/test/fourth')
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
xhr.send('name=QF666&age=18')
xhr.onload = function () {
    let res = JSON.parse(xhr.responseText)
    console.log(res)
}

ajax 中 get 和 post 的区别有哪些

1.携带参数的位置
a.GET: 直接在地址后面书写
b.POST: 在请求体内书写
2.携带参数的大小
a.GET: 2kb(左右)
b.POST: 原则上不限制大小, 但是服务器可以做出限制
3.携带参数的格式
a.GET: 只能携带查询字符串格式
b.POST: 原则上不限制格式, 但是需要在请求报文的 content-type 做出配置
4.安全性(相对)
a.GET: 明文发送, 相对不安全
b.POST: 暗文发送, 相对安全

猜你喜欢

转载自blog.csdn.net/sdasadasds/article/details/131107954
今日推荐