API
如何使用ajax
- 1-1 HTML和CSS实现页面
- 1-2 Ajax和Web服务器进行数据的异步交换
-
实现ajax
<script>
/* 实现ajax的前提
1.html页面
2.后端提供的数接口
3.DOM将获取的数据放在页面上 (有接口才有数据)*/
var url = `http://127.0.0.1:5500/mock/index.json`;
// 1.创建ajax的核心对象
var xhr =new XMLHttpRequest();
// 2.需要与服务器建立连接
xhr.open("get",url,true)
// 3.发送请求
xhr.send();
// 4.响应数据
xhr.onreadystatechange =function(){
if(xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText)
}
}
</script>
封装ajax:
function $ajax({url,success} ){
var xhr = new XMLHttpRequest();
xhr.open("get",url,true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState ==4 && xhr.status>=200&&xhr.status<=300){
var res = JSON.parse(xhr.responseText);
success(res)
}
}
}