XMLHttpRequest(ajax底层原理)

XMLHttpRequest(ajax底层原理)


<html>
  <head>
    <meta charset="utf-8">
    <title>title>
    <script>
    window.οnlοad=function (){
      let oBtn=document.getElementById('btn1');

      oBtn.οnclick=function (){
        //1.创建对象,此时xhr.readyState=0
        let xhr=new XMLHttpRequest();

        //2.连接,此时xhr.readyState=1
        xhr.open('GET', 'data/2.txt?a=12&b=5', true);

        //3.发送,此时xhr.readyState=2
        xhr.send();

        //4.接收,此时xhr.readyState=3/4(3是头接收完,4是体接收完)
        xhr.onreadystatechange=function (){
          if(xhr.readyState==4){    //此时只是接收到了回信,到不表示里面返回的是成功!
            alert('成功收到回信');
            if(
              (xhr.status>=200 && xhr.status<300)||
              xhr.status==304   //304——Not Modified也是成功!
            ){
              alert('回信里也是成功');
              console.log(xhr);    //内容见下图

              let json=JSON.parse(xhr.responseText);

              alert(json);
              console.log(json);
            }else{
              alert('失败');
            }
          }
        };
      };
    };
    script>
  head>
  <body>
    <input type="button" value="按钮" id="btn1">
  body>
html>

/* ./data/1.txt */
{"name": "zhangsan", "age": "16"}

XMLHttpRequest(ajax底层原理)_第1张图片
XMLHttpRequest对象
AJAX——onreadystatechange事件

readyState状态码:
0 初始状态 xhr对象刚创建完
1 连接 连接到服务器
2 发送请求 刚刚send完
3 接收完成 头接收完了
4 接收完成 体接收完了

status——http状态码:

1xx 消息
2xx 成功
3xx 重定向
▪ 301 Moved Permanently 永久重定向——下回不会再找他了
▪ 302 Move temporarily 临时重定向——下回依然会请求服务器
▪ 304 Not Modified 缓存、也算成功百度百科
4xx 请求错误
5xx 服务端错误
6xx+ 自定义

XMLHttpRequest包含信息查看

let xhr=new XMLHttpRequest();
console.log(xhr);
//在控制台看到XMLHttpRequest包含的所有信息
//例如readyState值、responseURl、status(http状态码)等等
//其中responeseText是返回的文本数据,responeseXML是返回XML数据

JSON.stringify()

{a: 12, b: 5}   =>    "{\"a\": 12, \"b\": 5}"
//JSON转字符串

JSON.parse()

"{\"a\": 12, \"b\": 5}" => {a: 12, b: 5}
//字符串转JSON

eval——不安全,不使用

//考虑兼容性,在IE678使用
              try{
                json=JSON.parse(xhr.responseText);
              }catch(e){
                json=eval('('+xhr.responseText+')');
              }

你可能感兴趣的:(javascript)