前后端交互-AJAX笔记
什么是 Ajax
通过在后台与服务器进行少量数据交换,Ajax 可以使用网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
Ajax 实例
1 | <script> |
XMLHttpRequest 对象
所有现代浏览器均支持 XMLHttpRequest 对象
XMLHttpRequest 用于在后台与服务器进行数据交换
创建 XMLHttpRequest 对象
1 | var xmlhttp = new XMLHttpRequest(); |
Ajax 向服务器发出请求
1 | xmlhttp.open('GET','test.php',true); |
方法
- open(method,url,async)
- method:请求的类型 GET 或 POST
- url : 文件在服务器上的位置
- async:true(异步)或 false (同步)
- send(string)
- string 仅用于 POST 请求
GET 请求
1 | xmlhttp.open("GET","test.php?id=1",true); |
POST 请求
1 | xmlhttp.open("POST","test.php",true); |
- setRequestHeader(header,value)
- header 请求头
- 请求头的值
Async=true
当 async = true 时
1 | <script> |
Ajax 服务器的响应
服务器响应
- responseText
- 获得字符串形式的响应数据
- responseXML
- 获得XML形式的响应数据
Ajax - onreadystatechange 事件
当请求被发送到服务器时,我们需要执行基于响应的任务。
每当 readyState 改变时,就会出发 onreadystatechange 事件。
- readyState 属性存有 XMLHttpRequest 的状态信息
- 0 : 请求未初始化
- 1:服务器连接已建立
- 2:请求已接收
- 3:请求处理中
- 4:请求已完成,且响应就绪
- status
- 200 : OK
- 404:未找到页面
- 其他状态码: https://www.runoob.com/http/http-status-codes.html
Ajax - Json
1 | <script> |
test.json
1 | [ |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.