您当前的位置: 首页 >  网络

知其黑、受其白

暂无认证

  • 0浏览

    0关注

    1250博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JS基础 网络请求

知其黑、受其白 发布时间:2022-02-18 20:14:59 ,浏览量:0

阅读目录
  • 基础知识
  • XMLHttpRequest
    • 基本使用
    • 响应类型
    • 响应结果
    • 使用示例
    • 发送表单
    • 封装请求类
  • FETCH
    • 请示步骤
      • 响应头解析
      • 响应内容解析
    • 实例操作
      • 发送请求 get
      • 发送请求 post

基础知识

浏览器天生具有发送HTTP请求的能力,比如在址栏输入内容,提交 FORM 表单等。 本章来学习通过JS程序来管理HTTP请求的能力。

使用JS脚本发送HTTP请求,不会带来页面的刷新,所以用户体验非常好。

XMLHttpRequest

使用XMLHttpRequest发送请求,是一种存在很久的方案。 现代浏览器支持使用 fetch 的异步请求方式,fetch 基于 promise 异步操作体验更好。

基本使用

使用XMLHttpRequest 发送请求需要执行以下几步

  • 使用 new XMLHttpRequest 创建 xhr 对象
  • xhr.open 初始化请求参数
  • xhr.send 发送网络请求
  • xhr.onload 监听请求结果
  • xhr.onerror 请求中断等错误发生时的处理
响应类型

通过设置 xhr.responseType 对响应结果进行声明,来对结果自动进行处理。

下面是可以使用的响应类型

类型说明text响应结果为文本json响应内容为JSON,系统会自动将结果转为JSON对象blob二进制数据响应documentXML DOCUMENT 内容 响应结果

xhr.onload 用于处理响应完毕后的处理

使用以下属性来处理结果

1、xhr.status 为HTTP状态码 如 404/422/403等,当为200时为正确响应 2、xhr.statusText HTTP状态码内容,200时为ok,404 为Not Found 3、xhr.response 服务器端响应的内容

使用示例

在这里插入图片描述


const xhr = new XMLHttpRequest()
xhr.timeout = 5000
xhr.open('GET', 'http://tt.cc/testData/user.php')
xhr.send()
xhr.onload = function () {
    if (xhr.status == 200) {
        console.log(xhr.response)
    } else {
        console.log(`${xhr.status}:${xhr.statusText}`)
    }
}
xhr.onerror = function (error) {
    console.log(error)
}

users.php

 "小明",
    2 => "李四",
    3 => "张三"
];
sleep(5);
echo $users[$_GET['id']];
发送表单

下面来使用 XMLHttpRequest 发送 POST 请求

后台服务 下面创建 users.php后台脚本(你可以使用你喜欢的后台脚本进行测试)

 {
            if (xhr.status == 200) {
                console.log(xhr.response)
            } else {
                console.log(`${xhr.status}:${xhr.statusText}`)
            }
        }
    }
  

在这里插入图片描述

封装请求类

下面结合 Promise 来构建一个 XHR 异步处理类,使异步请求操作的变得更简单。 在这里插入图片描述


class HD {
  options = {
    responseType: 'json',
  }
  constructor(method = 'GET', url, data = null, options) {
    this.method = method
    this.url = url
    this.data = this.formatData(data)
    Object.assign(this.options, options)
  }
  formatData(data) {
    if (typeof data != 'object' || data == null) data = {}
    let form = new FormData()
    for (const [name, value] of Object.entries(data)) {
      form.append(name, value)
    }

    return form
  }
  static get(url, options) {
    return new this('GET', url, null, options).xhr()
  }
  static post(url, data, options) {
    return new this('POST', url, data, options).xhr()
  }
  xhr() {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      xhr.open(this.method, this.url)
      xhr.responseType = this.options.responseType
      xhr.send(this.data)
      xhr.onload = function () {
        if (xhr.status != 200) {
          reject({ status: xhr.status, error: xhr.statusText })
        } else {
          resolve(xhr.response)
        }
      }
      xhr.onerror = function (error) {
        reject(error)
      }
    })
  }
}

// 使用HD.get静态方法发送GET请求
HD.get('http://tt.cc/testData/user.php?name=wgchen', {
    responseType: 'text',
  }).then((response) => {
    console.log(response)
  })

// 使用HD.post静态方法发送POST请求
let data = {title:'wgchen',url:'tt.cc'}

HD.post('http://tt.cc/testData/users.php', data, {
  responseType: 'json',
}).then((response) => {
  console.log(response)
})

  

users.php

 'ycc'],
    ['name' => 'willem']
];
echo json_encode($articles);
发送请求 get

下面使用 FETCH 发送 GET 请求

在这里插入图片描述



fetch(`http://tt.cc/testData/users.php`)
.then(response => {
    return response.json()
})
.then(articles => {
    console.log(articles)
})

  

因为 fetch 结果是 promise 所以也可以使用 async/await 操作



async function query() {
  const response = await fetch(`http://tt.cc/testData/users.php`)
  const articles = await response.json()
  console.log(articles)
}
query()

  

在这里插入图片描述

发送请求 post

发送POST请求需要设置请求头 Request header

发送请求

发送的JSON类型需要设置请求头为 application/json;charset=utf-8




async function post() {
    const response = await fetch(`http://tt.cc/testData/users.php`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
        },
        body: JSON.stringify({ name: 'wgchen' }),
    })
    if (response.ok) {
        const articles = await response.json()
        console.log(articles)
    }
}
post()

 

在这里插入图片描述

后台响应

因为前台发送的是非表单数据,而是 JSON 字符串所以后台使用 php://input 来接收数据

            
关注
打赏
1665558895
查看更多评论
0.1294s