关于javascript:JS发HTTP请求的方法

3次阅读

共计 2635 个字符,预计需要花费 7 分钟才能阅读完成。

文章仅作为集体学习过程的记录,知识点梳理,若有不谨严、不正确、须要补充的中央欢送指出。

AJAX
先创立一个 HTTP 申请

const Http = XMLHttpRequest();

确定申请要发送到的 url

cosnt url = 'https://segmentfault.com';

而后整合,发送申请

Http.open('GET', url, true); // 用于初始化一个申请,method,url,async
Http.send(); // 用于发送申请,调用后申请才会真的收回

POST 申请时,须要解决申请参数,须要更新的数据 data 作为 send()的参数。

Http.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // 来设置申请头
Http.onerror = function(){}; // 来解决异样
Http.abort(); // 终止一个申请,调用后 readyState 变为 0 

response 响应的注释,返回类型由 responseType 决定
responseType 响应的数据类型,默认为 text,可手动设置为 ””, “json”, “text”, “document”, “blob”, “arraybuffer”

事件回调
onreadystatechange 事件监听器对申请后果进行操作,属性变动时触发

Http.onreadystatechange = (e) => {console.log(Http.response);
}

判断申请是否胜利有两个属性,readyState 和 Status

Http.onreadystatechange = (e) => {if(this.readyState === 4 && this.status === 200) {console.log(Http.responseText);
    }
}

readyState 有五种值:

  • 0:UNSEND => 已创立,但 open()还未被调用
  • 1:OPENED => open()已被调用
  • 2:HEADERS_RECEIVED => send()已被调用,headers 和 status 可用
  • 3:LOADING => 加载中,领有局部数据
  • 4:DONE => 实现

onloadstart 在 ajax 申请之前 (1 <= readyState <= 2) 触发
onprogress 用资源总大小 total 和曾经加载的大小 loaded,计算加载进度
onload 资源加载实现触发,在其中解决返回值
onerror 资源加载失败触发,处理错误
ontimeout 申请超时调用,超时工夫用 timeout 属性设置

JQuery
须要先引入 jquery 库才能够应用

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  1. $.ajax
    最简略的办法之一,多个参数可选。get,post 等都可实现。

     $.ajax({
       url: 'https://segmentfault.com',
       type: 'GET', // or POST
       // data: data, // if the type is POST
       //dataType: JSON or HTML, XML, TXT, jsonp
       success: function(result) {console.log(result)
       },
       error: function(err) {console.log(err)
       }
     })
  2. $.get
    用来执行 GET 申请,有两个参数 端点和回调函数

     $.get(url, function(data, status){console.log(`${data}`);
     })
  3. $.post
    用来执行 POST 申请,有三个参数 端点,发送的数据和回调函数

     $.post(url, data, function(data, status){console.log(`${data} and status is ${status}`);
     })
  4. $.getJSON
    仅用于获取 json 个数数据

     $.getJSON(url, function(result){console.log(`${result}`);
     })
    

Fetch
一个功能强大的新的 web API,能发动异步申请。返回一个 Promise 对象,能够更聪慧的解决异步申请。Promise 具体介绍可查看 ES6 中 Promise 章节。

fetch(url, {
    method: "POST", // or GET
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(params), // POST 时,传递更新数据,GET 不须要
})
.then(data => {return data})
.catch(error => {return error})

Axios
开源的创立 HTTP 申请的库,也是返回一个 Promise。首先要引入 axios 能力应用。
终端 / 命令行输出

npm install axios --save

文件中引入

import axios from 'axios'

<script src='https://unpkg.com/axios/dist/axios.min.js'></script>

基于 axios,能够应用 GET 和 POST 来申请和发送数据
GET:

axios.get(url, params) // params 条件申请参数,可不填
.then(data => {console.log(data)})
.catch(err => {console.log(err)})

POST:

axios({
method: 'post', 
url: url, 
Content-Type: 'application/json', // multipart/form-data, application/x-www-form-urlencoded
data: {updateData}})
.then(data => {console.log(data)})
.catch(err => {console.log(err)})

参考资料:

  1. https://chinese.freecodecamp….
  2. https://cynthia0329.github.io…
  3. https://www.mzh.ren/comparing…
正文完
 0