目录
ajax是前后端通信的技术,函数
Ajax请求的4个步骤
<script>
// 1,创建xhr对象
var xhr=new XMLHttpRequest()
//2,调用open函数,规定请求的方法和URL地址
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
// 3,调用send函数,发起ajax请求
xhr.send()
// 4,监听onreadystagechange事件
xhr.onreadystatechange=function(){
// 4.1监听xhr对象的请求状态readystate;4.2监听服务器的响应状态status
// readystate的值从 0 ~ 4,一共 5 个状态
// 0:未初始化。尚未调用 open()
// 1:启动。已经调用 open(),但尚未调用 send()
// 2:发送。已经调用 send(),但尚未接收到响应
// 3:接收。已经接收到部分响应数据
// 4:完成。已经接收到全部响应数据,而且已经可以在浏览器中使用了
if(xhr.readyState===4&&xhr.status===200){
// 4.3打印服务器响应回来的数据xhr.responseText ,数据格式是JSON的字符串格式
console.log("hello"+xhr.responseText);
}
}
</script>
GET
携带数据和编码的方式
// get 方法带参数,拼接的参数叫查询字符串
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks?id=1')
POST
多一个步骤
<script>
// 1.创建xhr对象
var xhr = new XMLHttpRequest()
// 2调用xhr,发起post,和url地址确认
xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
// 3设置content-typeo属性
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
// 4 发送
xhr.send('bookname=水浒传&author=施耐庵&publisher=天津图书出版社')
// 5状态监听
xhr.onreadystatechange=function(){
if (xhr.readyState === 4 && xhr.status === 200)
console.log(xhr.responseText)
}
</script>
xhr
xhr的属性
1.responseType 和 response 属性:规定内容传播的格式
2.timeout 属性 :设置请求的超时时间(单位 ms)
3.withCredentials 属性:指定使用 Ajax 发送请求时是否携带 Cookie。 使用 Ajax 发送请求,默认情况下,同域时,会携带 Cookie;跨域时,不会
const url = './index.html';
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState != 4) return;
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.response);
}
};
xhr.open('GET', url, true);
// xhr.response和xhr.responseType =""和xhr.responseType ="text"都是规定传输内容是文本
// // xhr.responseType = '';
xhr.responseType = 'text';
// xhr.responseType = 'json';
xhr.timeout = 10000;
xhr.withCredentials = true;
xhr.send(null);
xhr的方法
1.abort 终止请求
2.setRequestHeader(),可以设置请求头信息
// const url = 'https://www.imooc.com/api/http/search/suggest?words=js';
//后端设置的json请求接口
const url = 'https://www.imooc.com/api/http/json/search/suggest?words=js';
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState != 4) return;
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.response);
}
};
xhr.open('POST', url, true);
//终止请求
// xhr.abort();
// 请求头中的 Content-Type 字段用来告诉服务器,浏览器发送的数据是什么格式的
// xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-Type', 'application/json');
// xhr.send(null);
// xhr.send('username=alex&age=18');
xhr.send(
JSON.stringify({
username: 'alex'
})
);
xhr事件
load事件:服务器完成响应
error事件:请求出现错误
abort事件:停止发送请求
timeout事件:响应超时
<script>
const url = 'https://www.imooc.com/api/http/search/suggest?words=js';
const xhr =new XMLHttpRequest();
// xhr.onload=()=>{
// // 事件一定响应了,所以不需要对readystate的状态进行判断,状态肯定是4
// // if(xhr.readyState!==4)return;
// if((xhr.status>=200&&xhr.status<300)||xhr.status===304){
// console.log('可以正常响应数据');
// console.log(JSON.parse(xhr.responseText).data);//{code: 200, data: Array(5)}
// }
// }
//可以改成和addEventListener一起使用
xhr.addEventListener('load',()=>{
// 事件一定响应了,所以不需要对readystate的状态进行判断,状态肯定是4
// if(xhr.readyState!==4)return;
if((xhr.status>=200&&xhr.status<300)||xhr.status===304){
console.log('可以正常响应数据');
console.log(JSON.parse(xhr.responseText).data);//{code: 200, data: Array(5)}
}
//这里如果用else报错,是服务器的响应出问题,跟请求没有关系
},false);
//error事件是对请求出错的时候进行处理,比如请求的服务器网站出错
xhr.addEventListener('error',()=>{
console.log("error");
},false);
//abort事件
xhr.addEventListener('abort',()=>{
console.log("abort");false
});
//timeout事件
xhr.addEventListener('timeout',()=>{
console.log("timeout");
});
xhr.open('GET',url, true );
xhr.send(null );
//发送请求后就会终止
// xhr.abort()
xhr.timeout=10;
// 2.setRequestHeader()
// 可以设置请求头信息
</script>
JSON前后端数据交换格式
是前后端内容数据交换的一种格式。有XML(不常用)和JSON(常用)
两种数据结构:对象和数组
json字符串格式:对象结构在 JSON 中表示为 { } 括起来的内容。数据结构为 { key: value, key: value, … } 的键值对结构。其中,key 必须是使用英文的双引号包裹的字符串,value 的数据类型可以是数字、字符串(也用双引号包裹)、布尔值、null、数组、对象6种类型
例如
{ "name":"runoob", "alexa":10000, "site":"www.runoob.com" }
var obj = JSON.parse('{ "name":"runoob", "alexa":10000, "site":"www.runoob.com" }');
console.log("obj",obj);//obj {name: 'runoob', alexa: 10000, site: 'www.runoob.com'}
数据转化
把数据对象转换为字符串的过程,叫做序列化,例如:调用 JSON.stringify() 函数的操作,叫做 JSON 序列化。
把字符串转换为数据对象的过程,叫做反序列化,例如:调用 JSON.parse() 函数的操作,叫做 JSON 反序列化。
<script>
const url = 'https://www.imooc.com/api/http/search/suggest?words=js';
const xhr =new XMLHttpRequest();
xhr.onreadystatechange=()=>{
if(xhr.readyState!==4)return;
if((xhr.status>=200&&xhr.status<300)||xhr.status===304){
console.log('可以正常响应数据');
// JSON的使用方法 使用parse
//获取的是数据格式是对象
console.log(JSON.parse(xhr.responseText).data);//{code: 200, data: Array(5)}
}
}
xhr.open(
'POST',
'https://www.imooc.com/api/http/search/suggest?words=js',
true
);
xhr.send(
JSON.stringify({name:"xiaoming",
age:18})
)
</script>