1.什么是ajax
Asynchronous JavaScript and XML
(异步的JavaScript 和XML)
- Ajax不是某种编程语言
是一种在无需重新加载整个网页的情况下,能够局部更新网页的技术 -
2.完整的原生ajax实现步骤
2.1创建ajax核心对象
var xhr = new XMLHttpRequest();
2.2与服务器建立连接
var url = “https://easy-mock.com/mock/5d67436624fd60626abfe91e/ajax/base“;
三个参数:url(请求地址)method(请求的方式 get post) async(同步、异步 是否异步)2.3发送请求
xhr.open(‘get’, url, true); //true 表示异步处理
xhr.send();2.3.1open(method,url,async)
规定请求的类型、URL 以及是否异步处理请求。
method:请求的类型;GET 或 POST
- url:文件在服务器上的位置
-
2.3.2send(string)
将请求发送到服务器。
-
2.4响应
xhr.onreadystatechange = function () {
响应函数
}<p id="name"></p><p id="age"></p><script>/* ajax 从服务器上获取数据的一种技术 是异步的1.创建ajax核心对象2.与服务器建立连接3.发送请求4.响应*//* JSON.parse() json格式的字符串转换为json对象 */var xhr=new XMLHttpRequest();var url="https://www.easy-mock.com/mock/5d67436224fd60626abfe906/ajax/base";xhr.open('get',url,true) //true 异步xhr.send()xhr.onreadystatechange=function(){/* console.log(xhr.readyState)console.log(xhr.status) */if(xhr.readyState==4 && xhr.status==200){ //请求已完成 200:请求成功var res=JSON.parse(xhr.responseText);console.log(res.data.name)var name=document.getElementById("name")name.innerHTML=res.data.name;}}/*1.异步 同步 网络请求到底是用同步还是异步2.ajax使用场景3.如何使用ajax*/</script>
3.同步和异步
同步:就是客户端向服务器发送请求的过程中,用户不可以进行其他操作
异步:就是客户端向服务器发送请求的过程中,用户可以进行其他操作
<script>
console.log("1")
setTimeout(function(){
console.log("http")
},1000)
console.log("2")
</script>
输出结果:
1
2
http
4.同源策略
不同的域名不能相互访问对象
域名:协议、子域名、主域名、端口号四部分组成,有一个不同就不是相同域
- 协议相同
- 域名相同
- 端口相同
