一.Ajax概述
1.1AJAX 简介
AJAX 全称为Asynchronous JavaScript And XML,就是异步的JS 和XML
通过AJAX 可以在浏览器中向服务器发送异步请求,最大的优势:无刷新获取数据
AJAX 不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式
1.2AJAX 的特点
AJAX 的优点:
1.可以无需刷新页面而与服务器端进行通信
2.允许你根据用户事件来更新部分页面内容
AJAX 的缺点:
1.没有浏览历史,不能回退
2.存在跨域问题(同源)
3.SEO 不友好
二.HTTP相关问题
2.1 HTTP 请求报文
1.请求行
method url 协议版本
GET /product_detail?id=2 HTTP/1.1
POST /login HTTP/1.1
2.多个请求头
Host: www.baidu.com
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded 或者application/json
3.请求体
username=tom&pwd=123
{“username”: “tom”, “pwd”: 123}
2.2 HTTP 响应报文
1.响应状态行: status statusText
HTTP/1.1 200 OK
2.多个响应头
Content-Type: text/html;charset=utf-8
Set-Cookie: BD_CK_SAM=1;path=/
Cache-Control: private
3.响应体
html 文本/json 文本/js/css/图片…
2.3 post 请求体参数格式
Content-Type: application/x-www-form-urlencoded;charset=utf-8
用于键值对参数,参数的键值用=连接, 参数之间用&连接
例如: a=100&b=200&c=300
name=%E5%B0%8F%E6%98%8E&age=12
Content-Type: application/json;charset=utf-8
用于 json 字符串参数
例如: {"a": 100, "b": 200,"c":300}
{"name": "%E5%B0%8F%E6%98%8E", "age": 12}
Content-Type: multipart/form-data
用于文件上传请求
三. XHR使用
get方式:
//绑定事件
btn.onclick = function(){
//1. 创建对象
const xhr = new XMLHttpRequest();
//2. 初始化 设置请求方法和 url
xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');
//3. 发送
xhr.send();
//4. 事件绑定 处理服务端返回的结果
// on when 当....时候
// readystate 是 xhr 对象中的属性, 表示状态 0 1 2 3 4
// change 改变
xhr.onreadystatechange = function(){
//判断 (服务端返回了所有的结果)
if(xhr.readyState === 4){
//判断响应状态码 200 404 403 401 500
if(xhr.status >= 200 && xhr.status < 300){ // 2xx 成功
//处理结果 行 头 空行 体
// console.log(xhr.status);//状态码 // 响应
// console.log(xhr.statusText);//状态字符串
// console.log(xhr.getAllResponseHeaders());//所有响应头
// console.log(xhr.response);//响应体
result.innerHTML = xhr.response; //设置 result 的文本
}else{
}
}
}
}
post方式:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1:8000/server');
//设置请求头
// Content-Type 用来设置请求体内容的类型
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('name','atguigu');
// Content-Type属于预定义的头,name属于自定义的头
//3. 发送
xhr.send('a=100&b=200&c=300');
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
result.innerHTML = xhr.response;
}
}
}
JSON方式:
const xhr = new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType = 'json';
xhr.open('GET','http://127.0.0.1:8000/json-server');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
// 1. 手动对数据转化
// let data = JSON.parse(xhr.response);
// console.log(data);
// 2. 自动转换 服务端进行数据处理
console.log(xhr.response);
result.innerHTML = xhr.response.name;
}
}
}
四. 跨域-同源-jsonp-CORS
看这个:https://blog.csdn.net/weixin_43190804/article/details/123042715
参考:YK菌
https://blog.csdn.net/weixin_44972008/article/details/113772348