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:文件在服务器上的位置
  • async:true(异步)或 false(同步)

    2.3.2send(string)

    将请求发送到服务器。

  • string:仅用于 POST 请求

    2.4响应

    xhr.onreadystatechange = function () {
    响应函数
    }

    1. <p id="name"></p>
    2. <p id="age"></p>
    3. <script>
    4. /* ajax 从服务器上获取数据的一种技术 是异步的
    5. 1.创建ajax核心对象
    6. 2.与服务器建立连接
    7. 3.发送请求
    8. 4.响应
    9. */
    10. /* JSON.parse() json格式的字符串转换为json对象 */
    11. var xhr=new XMLHttpRequest();
    12. var url="https://www.easy-mock.com/mock/5d67436224fd60626abfe906/ajax/base";
    13. xhr.open('get',url,true) //true 异步
    14. xhr.send()
    15. xhr.onreadystatechange=function(){
    16. /* console.log(xhr.readyState)
    17. console.log(xhr.status) */
    18. if(xhr.readyState==4 && xhr.status==200){ //请求已完成 200:请求成功
    19. var res=JSON.parse(xhr.responseText);
    20. console.log(res.data.name)
    21. var name=document.getElementById("name")
    22. name.innerHTML=res.data.name;
    23. }
    24. }
    25. /*
    26. 1.异步 同步 网络请求到底是用同步还是异步
    27. 2.ajax使用场景
    28. 3.如何使用ajax
    29. */
    30. </script>

3.同步和异步

同步:就是客户端向服务器发送请求的过程中,用户不可以进行其他操作
异步:就是客户端向服务器发送请求的过程中,用户可以进行其他操作

  1. <script>
  2. console.log("1")
  3. setTimeout(function(){
  4. console.log("http")
  5. },1000)
  6. console.log("2")
  7. </script>
  8. 输出结果:
  9. 1
  10. 2
  11. http

4.同源策略

不同的域名不能相互访问对象
域名:协议、子域名、主域名、端口号四部分组成,有一个不同就不是相同域

  • 协议相同
  • 域名相同
  • 端口相同