AJAX Asynchronous JavaScript and XML
异步的 JavaScript 和 XML。
慕课网:https://www.imooc.com/video/5644
跨域 (同源策略)
1 | Access-Control-Allow-Origin * |
NGINX 配置解决跨域
1 | add_header Access-Control-Allow-Methods *; |
简单请求与非简单请求
- 简单请求
GET
HEAD
POST
且 请求 header 无自定义头
且 Content-Type 为 text/plain
multipart/from-data
application/x-www-form-urlencoded
- 非简单请求
PUT
DELETE
JSON 格式的 AJAX
有自定义头
简单请求 先发送,后验证
非简单请求 先发送 OPTION 请求,通过验证再发送请求
1. 创建 XMLHttpRequest 对象 (XHR)
1 | <button id="search">按钮名字</button> |
1 | document.getElementById("search").onclick=function(){ |
2. 发送请求 open send
1 | xmlHttp.open("method", "url", true); // 第三个参数为 async,默认为 true |
3. 获取响应
1 | // 字符串形式的响应 |
其他方法
1 | .statusText 以文本形式返回 HTTP 信息 |
判断状态之后再操作 DOM
1 | xmlHttp.onreadystatechange=function() |
- 0: 请求未初始化
- 1: 服务器连接已建立
- 2: 请求已接收
- 3: 请求处理中
- 4: 请求已完成,且响应已就绪
JSON 解析
1 | JSON.parse("JSON 字符串"); |
jQuery
1 | $(document).ready(function(){ |