前端使用Javascript获取数据并绑定数据(校园团队合作版)

520 阅读1分钟

我们在学校进行编程技能的学习的时候难免会碰到要小组合作进行项目开发,从我个人的角度来看肯定是越高级的技术越好了。

可是当你要涉及到团队开发的时候就不能这样了,否则全队的任务就压在你一个人身上会非常难受,别人也学不到东西。

今天我来分享一个我的解决方案,我目前要做一个类携程的项目,需要带领七个人的团队进行开发,我们班是Java班,所以Java方向的不是很大问题,但前端我虽然会很多技术,但我的同学们都基本上大学都是玩过来的,前端基础基本为0,所以我的技术选型是:

HTML + CSS + JavaScript + Ajax + Spring Boot + Mybatis-plus

很明显前端是在刀耕火种的年代,但也没办法,凑合着用吧。

我安排了三个后端两个前端一个啥都不会的女生去写我们要交的会议记录等表格。

现在主流的获取数据的方法有三种,我这里介绍两种先:

  1. Ajax
  2. fetch
  3. axios

我们为了专注与前端,我们使用json-server这个库,就不写后端了:

image-20220628194518006

一、Ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box{
            width: 100px;
            height: 100px;
            background-color: aqua;
        }
    </style>
</head>
<body>
    <div id="box" class="box"></div>
    <button onclick="showPicture()">显示图片</button>
</body>
<script>
    const showPicture = ()=>{
        // 创建一个XMLHttpRequest对象,定义好访问的方法和地址
        const xhr = new XMLHttpRequest()
        const method = 'GET'
        const url = 'http://localhost:3000/picture'
​
        // 做请求成功的处理
        xhr.onreadystatechange = ()=>{
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    const data = JSON.parse(xhr.responseText)
                    const picture = data[0]
                    console.log(picture)
                    document.getElementById('box').style.backgroundImage = `url(${picture})`
                    document.getElementById('box').style.backgroundSize = `100%`
                }
            }
        }
​
        // 发送
        xhr.open(method,url,true)
        xhr.send(null)
    }
</script>
</html>

Ajax剖析:

open(method,url,async)
规定请求的类型、URL 以及是否异步处理请求。
​
- method:请求的类型;GETPOST
- url:文件在服务器上的位置
- asynctrue(异步)或 false(同步)
​
send(string)
将请求发送到服务器。
​
- string:仅用于 POST 请求
​
如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。
responseText  获得字符串形式的响应数据,如果来自服务器的响应并非 XML,请使用 responseText 属性。
responseXML   获得 XML 形式的响应数据。
​
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
下面是 XMLHttpRequest 对象的三个重要的属性:
1. onreadystatechange 
- 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
2. readyState 
- 存有 XMLHttpRequest 的状态。
- 从 04 发生变化。
  - 0: 请求未初始化
  - 1: 服务器连接已建立
  - 2: 请求已接收
  - 3: 请求处理中
  - 4: 请求已完成,且响应已就绪
status  
- 200: "OK"
- 404: 未找到页面
​
在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
当 readyState 等于 4 且状态为 200 时,表示响应已就绪,如上图代码。

image-20220628205007096

image-20220628205205365

二、fetch

const fetchData = async ()=>{
  await fetch('http://localhost:3000/picture')
  .then(json => json.json())
  .then(resp => console.log(resp[0]));
}
Fetch API主要暴露了三个接口一个方法。
- Request(资源请求)
- Response(请求的响应)
- Headers(Request/Response头部信息)
- fetch()(获取资源调用的方法)
// 实例化一个Request实例
// 第一个参数一般指资源路径
// 第二个参数可以理解为请求的配置项,包含头部信息和http请求一些关键配置(请求类型、参数...)
let requestInstance = new Request('/hello', {
    method: 'post',
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    },
    body: '{"hello": "world"}'
})
// fetch方法参数同Request实例
// 第一个参数为url或者Request实例
// 第二个参数为请求配置项
fetch(requestInstance).then(response => {
    // 返回的是一个Response的实例
    // 调用Response实例的序列化方法,序列化成json,返回值是一个promise
    // 序列化方法有 json,text,formData,blob,arrayBuffer,redirct
    let result = response.json()
    result.then(res => {
        consolee.log(res)
    })
})

POST json

const url = 'http://127.0.0.1:3000'
let testRequest = new Request(url + '/test', {
    method: 'post',
    headers: {
        'Content-Type': 'application/json;charset=utf-8;'
    },
    body: JSON.stringify({a: 1})
})
fetch(testRequest).then(response => {
    let result = response.text()
    result.then(res => {
        console.log(res)
    })
})

POST Header

let formRequest = new Request(url + '/form', {
    method: 'post',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
    },
    body: 'a=1&b=2'
})
fetch(formRequest).then(response => {
    let result = response.json()
    result.then(res => {
        console.log(res)
    })
})

POST FormData

let formRequest = new Request(url + '/form', {
    method: 'post',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
    },
    body: 'a=1&b=2'
})
fetch(formRequest).then(response => {
    let result = response.json()
    result.then(res => {
        console.log(res)
    })
})

POST 文件上传

<template>
    <input type="file" id="uploadFile">
</template>
<script>
let $input = document.getElementById('uploadFile')
// 监听文件上传
$input.addEventListener('change', e => {
    let file = e.target.files[0]
    handleUploadFile(file)
})
​
function handleUploadFile (file) {
    let bean = new FormData()
    bean.append('file', file)
    bean.append('hello', 'world')
    let uploadFileRequest = new Request(`${url}/upload`, {
        method: 'post',
        headers: {
            'Content-Type': 'multipart/formdata'
        },
        body: bean
    })
    fetch(uploadFileRequest).then(response => {
        let result = response.text()
        result.then(res => {
            console.log(res)
        })
    })
}
</script>