JS请求

AJAX

XMLHttpRequest对象

 let xhr = new XMLHttpRequest()

发送请求

 xhr.open('GET','http://xxx.xxx:xxx')
 xhr.send()

对象方法

方法

描述

new XMLHttpRequest()

创建新的XMLHttpRequest

abort()

取消当前对象方法

getAllResponseHeaders()

返回头部信息

getResponseHeader()

返回特定的头部信息

open(method,url,async,user,psw)

规定请求 method:请求类型 GET 或 POST url:文件位置 async:true(异步)或 false(同步) user:可选的用户名 psw:可选的密码

send()

向服务器发送请求,用于GET请求

setRequestHeader()

将标签/值对添加到要发送的标头

对象属性

属性

描述

onload

定义接收到(加载)请求时要调用的函数

onreadystatechange

定义当readyState属性变化时调用的函数

readyState

保存XMLHttpRequest的状态 0:请求未初始化 1:服务器连接已建立 2:请求已收到 3:正在处理请求 4:请求已完成且响应已就绪

responseText

以字符串形式返回数据响应

responseXML

以XML数据返回响应数据

status

返回请求的状态号: 200: "OK" 403: "Forbidden" 404: "Not Found"

statusText

返回状态文本 (比如 ‘OK’)

实例

 <body>
     <button>点击发送请求</button>
     <div class="box"></div>
     <script>
       const btn = document.querySelector("button");
       const box = document.querySelector(".box");
       btn.addEventListener("click", function () {
         //创建对象
         const xhr = new XMLHttpRequest();
         //设置请求方式
         xhr.open("GET", "http://127.0.0.1:8000/server?a=100");
         //发送请求
         xhr.send();
         //监听响应
         // on where 当...的时候
         //readystate 是xhr对象的属性,表示状态 0 1 2 3 4
         //0 未初始化 1 准备 2 发送 3 接收 4 完成
         //change 改变
         xhr.onreadystatechange = function () {
           //判断(服务器返回了所有结果)
           if (xhr.readyState === 4) {
             //判断响应码状态码 200 成功 404 失败
             if (xhr.status >= 200 && xhr.status < 300) {
               //获取服务器返回的数据
               console.log(xhr.status); //状态码
               console.log(xhr.statusText); //状态字符串
               console.log(xhr.response); //响应数据
               box.innerHTML = xhr.response;
             }
           }
         };
       });
     </script>
   </body>

请求

向服务器发送请求,我们使用XMLHttpRequest 对象的 open()send()方法

GET

实例:

 xhttp.open("GET", "http://xxx", true);
 xhttp.send();
  • 上述例子可能会得到一个缓存的结果 因此我们可以给url添加一个唯一的ID

 xhttp.open("GET", "http://xxx" + Math.random(), true);
 xhttp.send();
  • 如果需要用GET方法来发送信息,要在url中添加信息

 xhttp.open("GET", "demo_get2.asp?fname=Bill&lname=Gates", true);
 xhttp.send();

POST

实例:

 xhttp.open("POST", "demo_post.asp", true);
 xhttp.send();

如果需要POST数据,需要通过setRequestHeader()添加一个HTTP头部,然后在send()方法中规定发送数据

 xhttp.open("POST", "ajax_test.asp", true);//启用异步发送
 xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 //在send中添加数据
 xhttp.send("fname=Bill&lname=Gates");

url -服务器上的文件

open()方法的url参数,是服务器上文件的地址

 xhttp.open("GET", "ajax_test.asp", true);

异步- true还是 false

如需异步发送请求 open()方法的async参数必需设置为true:

 xhttp.open("GET", "ajax_test.asp", true);
  • 通过异步发送,javaScript不必等待服务器响应

    • 在等待服务器响应时执行其他脚本

    • 当响应时就绪数处理响应

取消请求

abort()取消发sing

 let x = new XMLHttpRequest();
 x.abort();

重复请求问题

  • 设置一个变量标记 一开始初始值为flase

  • 但按钮点击时判断 标记的值 使用abort来取消请求

  • 当请求的readyState状态 === 4时 使标记为true

  • 若再次点击就会触发abort

实例:

 <script>
       const btns = document.querySelectorAll("button");
       let x = null;
       //表示变量
       let isSending = false; //是否正在发送请求
       btns[0].addEventListener("click", function () {
         //判断标识变量
         if (isSending) x.abort();
         x = new XMLHttpRequest();
         //修改属性
         isSending = true;
         x.open("GET", "http://127.0.0.1:8000/time");
         x.send();
         x.onreadystatechange = function () {
           if (x.readyState === 4) {
             isSending = false;
             console.log(x.response);
           }
         };
       });
     </script>

响应

onreadystatechange属性

  • readyState 属性保存XMLHttpRequest的状态

  • onreadystatechange属性定义了一个回调函数,当readyState改变执行该函数

  • status属性和statusText属性保存XMLHttpRequest对象的状态

  xhr.onreadystatechange = function () {
         //readystate 是xhr对象的属性,表示状态 0 1 2 3 4
         //0 未初始化 1 准备 2 发送 3 接收 4 完成
           if (xhr.readyState === 4) {
             //判断响应码状态码 200 成功 404 失败
             if (xhr.status >= 200 && xhr.status < 300) {
               //获取服务器返回的数据
               console.log(xhr.status); //状态码
               console.log(xhr.statusText); //状态字符串
               console.log(xhr.response); //响应数据
               box.innerHTML = xhr.response;
             }
           }
         };

响应超时和网络异常

  • ontimeout响应超时 需要先对对象设置timeout设置超时时间

  • onerror网络异常

实例:

 <script>
       const box = document.querySelector(".box");
       const btn = document.querySelector("button");
       btn.addEventListener("click", function () {
         const xhr = new XMLHttpRequest();
         //超时设置
         xhr.timeout = 2000;
         //超时回调
         xhr.ontimeout = function () {
           alert("超时");
         };
         //网络异常
         xhr.onerror = function () {
           alter("网络异常");
         };
         xhr.open("get", "http://127.0.0.1:8000/time");
         xhr.send();
         xhr.onreadystatechange = function () {
           if (xhr.readyState === 4) {
             if (xhr.status >= 200 && xhr.status < 300) {
               box.innerHTML = xhr.response;
             }
           }
         };
       });
     </script>

json响应问题

  • 需要先设置responseType = "json"设置相应体的数据

  • 若设置了相应体数据,则会自动转换 使用xhr.response

  • 若没有设置则需要手动对数据转换 JSON.parse(xhr.response)

实例:

 <script>
       const box = document.querySelector(".box");
       window.onkeydown = function () {
         const xhr = new XMLHttpRequest();
         //设置相应体数据
         xhr.responseType = "json";
         // 发起请求
         xhr.open("GET", "http://127.0.0.1:8000/json-server");
         xhr.send();
         // 监听响应
         xhr.onreadystatechange = function () {
           if (xhr.readyState === 4) {
             if (xhr.status >= 200) {
               //   console.log(xhr.response);
               //   box.innerHTML = xhr.response;
               //手动对数据转换
               //   let data = JSON.parse(xhr.response);
               //   console.log(data);
               //   box.innerHTML = data.name;
               //自动转换(需要在前面做一个设置)
               console.log(xhr.response);
               box.innerHTML = xhr.response.name;
             }
           }
         };
       };
     </script>



JS请求
http://localhost:8090//archives/jsqing-qiu
作者
傅凯风
发布于
2024年11月06日
许可协议