首页 > 其他分享 >JS基础 网络请求

JS基础 网络请求

时间:2023-03-24 13:01:55浏览次数:37  
标签:请求 响应 网络 JS 发送 xhr data response


阅读目录

  • 基础知识
  • 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

二进制数据响应

document

XML DOCUMENT 内容

响应结果

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

使用以下属性来处理结果

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

使用示例

JS基础 网络请求_前端

<script>
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)
}
</script>

users.php

<?php

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

发送表单

下面来使用 XMLHttpRequest 发送 POST 请求

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

<?php
echo $_POST['title'];

前端异步请求

<form action="" id="form">
    <input type="text" name="title" />
    <input type="submit" />
</form>

<script>
    const form = document.getElementById('form')

    form.addEventListener('submit', function () {
        //阻止默认提交行为
        event.preventDefault()

        post('http://tt.cc/testData/users.php', new FormData(this))
    })

    function post(url, data) {
        const xhr = new XMLHttpRequest()
        xhr.open('POST', url)
        xhr.send(data)
        xhr.onload = () => {
            if (xhr.status == 200) {
                console.log(xhr.response)
            } else {
                console.log(`${xhr.status}:${xhr.statusText}`)
            }
        }
    }
</script>

JS基础 网络请求_json_02

封装请求类

下面结合 Promise 来构建一个 XHR 异步处理类,使异步请求操作的变得更简单。

JS基础 网络请求_json_03

<script>
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)
})

</script>

users.php

<?php

echo json_encode($_POST);

FETCH

FETCH是JS升级后提供的更简便的网络请求的操作方法,内部使用 Promise 来完成异步请求。

  • response.json() 接收 JSON 类型数据
  • response.text() 接收 TEXT 类型数据
  • response.blog() 接收 Blog 二进制数据

请示步骤

使用 fetch 方法发送异步请求需要分以下两步操作

响应头解析

第一步对服务器返回的响应头进行解析,会接到 Response 类创建的对象实例,里面包含以下属性。

  • status:HTTP状态码
  • ok:状态码为 200-299 时为 true 的布尔值

响应内容解析

第二步对返回的保存在 response.body 中的响应结果进行解析,支持了以下几种方式对结果进行解析。

  • response.json() 接收 JSON 类型数据
  • response.text() 接收 TEXT 类型数据
  • response.blog() 接收 Blog 二进制数据

以上方法不能同时使用,因为使用一个方法后数据已经被处理,其他方法就不可以操作了

实例操作

下面来体验使用 fetch 发送请求

后台服务

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

<?php
$articles = [
    ['name' => 'wgchen'],
    ['name' => 'ycc'],
    ['name' => 'willem']
];
echo json_encode($articles);

发送请求 get

下面使用 FETCH 发送 GET 请求

JS基础 网络请求_php_04

<script>

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

</script>

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

<script>

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

</script>

JS基础 网络请求_php_05

发送请求 post

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

发送请求

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

<script>


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()

</script>

JS基础 网络请求_网络_06

后台响应

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

<?php
echo file_get_contents('php://input');


标签:请求,响应,网络,JS,发送,xhr,data,response
From: https://blog.51cto.com/u_13571520/6147114

相关文章

  • JS基础 空间坐标
    阅读目录视口与文档视口与文档尺寸几何尺寸方法列表getComputedStylegetBoundingClientRectgetClientRects坐标点元素元素集合底层元素滚动控制方法列表文档滚动位置元素滚......
  • JS基础 任务管理
    阅读目录任务管理原理分析脚本加载定时器微任务实例操作进度条任务分解任务管理JavaScript语言的一大特点就是单线程,也就是说同一个时间只能处理一个任务。为了协调事件、......
  • JS基础 模块设计
    阅读目录模块设计使用分析实现原理基础知识标签使用模块路径延迟解析模块默认运行在严格模式模块都有独立的顶级作用域预解析导入导出导出模块具名导入批量导入导入建议别名......
  • JS基础 原型与继承
    阅读目录原型基础原型对象使用数组原型对象的concat方法完成连接操作默认情况下创建的对象都有原型。以下x、y的原型都为元对象Object,即JS中的根对象创建一个极简对象(......
  • HTTP请求方法
    根据HTTP标准,HTTP请求可以使用多种请求方法。HTTP1.0定义了三种请求方法:GET,POST和HEAD方法。HTTP1.1新增了六种请求方法:OPTIONS、PUT、PATCH、DELETE、TRACE......
  • requireJS 源码(二) data-main 的加载实现
    requireJS源码(二)data-main的加载实现(一)requireJs的整体结构:requireJS源码前192行,是一些变量的声明,工具函数的实现以及对三个全局变量(requirejs,require,def......
  • requireJS 源码(一) require() 为何可以全局使用
    requireJS源码(一)require()为何可以全局使用requireJS源码加注释总共不到2100行。我看的requireJs版本是2.19。 总体结构如下。......
  • requireJS 源码(三) data-main 的加载实现
    requireJS源码(三)data-main的加载实现(一)入口通过data-main去加载JS模块,是通过  req(cfg) 入口去进行处理的。为了跟踪,你可以在此加断点进行调试跟......
  • Vue.js 路由简介
    路由理解:一个路由(route)就是一组映射关系(key-value),多个路由需要路由器(router)进行管理。前端路由:key是路径,value是组件。......
  • 查看网络情况
    目录ping查看网络联通情况telnet查看端口打开情况netstat查看端口占用情况ping查看网络联通情况C:\>ping/?用法:ping[-t][-a][-ncount][-lsize][-f][-iTTL]......