ajax

87 阅读3分钟

AJAX

前端通过ajax向后端发送请求,得到想要的数据。

创建ajaxd 的步骤:

1,创建ajax:const xhr = new XMLHttpRequest()

2,向ajax配置数据:xhr.open('请求的方式','请求的地址','配置当前请求是否为异步(true为异步默认值)')

3,发送请求:xhr.send()

4,接收响应:xhr.onload = function() {console.log(xhr.responseText)}

ajax异步书写问题:

注:顺序来源于创建步骤

异步:1 2 3 4

1,创建ajax:同步代码

2,配置信息:同步代码(接收配置的是异步)

3,发送请求:同步发送请求,接收为异步(在接收前就会执行后续的同步代码,后面不在赘述)

4,配置接收响应

接收到服务器响应

// 1. 创建 ajax     (同步代码)
const xhr = new XMLHttpRequest()
// 2. 配置信息      (同步代码)
xhr.open('GET', 'http://localhost:8888/test/first', true)
// 3. 发送请求      (同步发送, 异步接收)
xhr.send()
// 4. 接收到 服务端的响应   (同步代码)
xhr.onload = function () {
console.log(xhr.responseText)
}

异步:1 2 4 3

1,创建

2,配置信息,接收配置为异步

4,书写接收到服务器响应的相应代码

3,发送请求

得到服务器响应

// 1. 创建 ajax     (同步代码)
const xhr = new XMLHttpRequest()
// 2. 配置信息      (同步代码)
xhr.open('GET', 'http://localhost:8888/test/first', true)
// 4. 接收到 服务端的响应   (同步代码)
xhr.onload = function () {
console.log(xhr.responseText)
}
// 3. 发送请求      (同步发送, 异步接收)
xhr.send()

同步:1 2 4 3

1,创建,

2,配置信息,将接收配置为 同步

4,书写接收到服务端响应的代码

3,发送请求

得到服务端的响应

// 1. 创建 ajax     (同步代码)
const xhr = new XMLHttpRequest()
// 2. 配置信息      (同步代码)
xhr.open('GET', 'http://localhost:8888/test/first', false)
// 4. 接收到 服务端的响应   (同步代码)
xhr.onload = function () {
console.log(xhr.responseText)
}
// 3. 发送请求      (同步发送, 异步接收)
xhr.send()

同步:1 2 3 4

1,创建

2,配置信息,将将接收配置为 同步

3,发送请求(同步发送,同步接收,接收会触发onload,但此时没有onload)

4,书写接收到服务端响应的代码(onload,此时服务器不会再有回应)

onload未执行

// 1. 创建 ajax     (同步代码)
const xhr = new XMLHttpRequest()
// 2. 配置信息      (同步代码)
xhr.open('GET', 'http://localhost:8888/test/first', false)
// 3. 发送请求      (同步发送, 异步接收)
xhr.send()
// 4. 接收到 服务端的响应   (同步代码)
xhr.onload = function () {
console.log(xhr.responseText)
}
ajax的状态码:

用一个数字,表明ajax执行到那一步了

0:表明ajax刚刚创建成功;

1:表明ajax刚刚配置成功;

2:表明ajax发送成功(还没有接收到响应);

3:表明服务器端接收到请求,并反馈给我们一个响应,此时浏览器正在解读响应的内容;

4:表明服务器端,接收请求,并返回一个响应,且浏览器解读完成。

const xhr = new XMLHttpRequest()
// 2. 配置信息      (同步代码)
xhr.open('GET', 'http://localhost:8888/test/first')
xhr.onreadystatechange = function () {
// console.log(xhr.readyState)
    if (xhr.readyState === 2) {
        // ajax 请求成功, 但还没有响应
        console.log(xhr.responseText)
    }
    if (xhr.readyState === 3) {
    // 响应回来了, 但浏览器还在解读
        console.log(xhr.responseText)
    }
    if (xhr.readyState === 4) {
    // 响应回来了, 解读也完成
        console.log(xhr.responseText)
    }
}
// 3. 发送请求      (同步发送, 异步接收)
xhr.send()
ajax请求方式get和post的区别:

1,参数的携带位置:

get => 将参数拼接到路径后,参数和路径之间使用问号? 分割;

post => 需要将参数,请求体内书写(xhr.send()小括号内部书写);

2,参数大小: get => 2kb 左右;

post => 原则上没有限制,服务端可以限制参数大小;

3,参数格式: get => 正常写一个查询字符串(key = value & key2 = value2);

post => 再传参时,需要再请求头内设置 content-type;

4,安全性(相对安全性)

get => 明文传输,相对不安全;

post => 暗文传输,相对安全(相对于get)。