前端知识总结(ajax)
1.手写XMLHttpRequest发起请求
const xhr=new XmlHttpRequest(); xhr.open(get,/url,true); xhr.onreadystatechange=function(){ if(xhr.readystate===4){ if(xhr.status===200){ alert(xhr.responseText); } } }; xhr.send();
2.xhr.status
2xx:表示成功处理请求
3xx:需要重定向,浏览器直接跳转,如301 302 304
4xx:客户端请求错误 如404 403
5xx:服务器端错误
3.跨域
1.jsonp实现跨域
<script>可以绕过跨域限制
服务器可以任意动态拼接数据返回
所以,<script>就可以获得跨域的数据,只要服务端愿意返回。
<script> window.callback=function(data){ console.log(data); } </script> <script src=xxxxxx></script> //将返回callback({x:100,y:200})
2.cors实现跨域
服务器设置http header
response.setHeader("Access-Control-Allow-Origin","http://localhost:8011"); response.setHeader("Access-Control-Allow-Headers","X-Requested-With"); response.setHeader("Access-Control-Allow-Methods","Put,Post,Get,Delete,Options"); //接收跨域的cookie response.setHeader("Access-Control-Allow-Credentials","true");
4.Cookie,localStorage和sessionStorage
1.localstorage用于永久存储数据,除非代码或手动删除
2.sessionStorage存储的数据只存在于当前会话,浏览器关闭则数据清空
3.一般用localstorage会更多一些
4.cookie的存储限制为4k,而localstorage和sessionstorage的存储限制为5M
5.cookie将会随http请求发送出去,而localstorage和sessionStorage不会随http请求发送