有关AJAX的记忆

42 阅读2分钟

在写JS代码时,我们用link rel="stylesheet" href="xxx"请求 CSS 内容,用 script src="xxx" 请求 JS 内容,用 img src=" xxx" 请求图片内容,但JS并没有提供一种特定方式来请求JSON内容,由此便产生了一种通用的请求任意内容的方法AJAX:async(异步的)、JS、And、XML。比如以下案例,点击页面上的button时会输出json内容:

if (path === '/') { //响应码 response.statusCode = 200 //响应头 //Content-Type告诉浏览器,我给你发送的内容是什么类型 response.setHeader('Content-Type', 'text/html;charset=utf-8') // 符合 HTML 语法的字符串 //响应体 消息体 response.write(

hello

点我
姓名
年龄


) //响应结束,响应给用户 response.end() } else if (path === '/style.css') { response.statusCode = 200 response.setHeader('Content-Type', 'text/css;charset=utf-8') // 符合 CSS 语法的字符串 response.write(h1{color: blue;}`) response.end() } else if (path === '/main.js') { response.statusCode = 200 response.setHeader('Content-Type', 'text/javascript;charset=utf-8') // 符合 JS 语法的字符串

//以下用到AJAX的简版代码
// response.write(`
//   const btn = document.querySelector('#btn')
//   btn.addEventListener('click', () => {
//     const xhr = new XMLHttpRequest()   //构造一个请求实例,请求/data json数据
//     xhr.open('GET', '/data')           //配置请求
//     xhr.onload = () => {               //监听——成功
//       console.log('请求成功')
//       console.log(xhr.responseText)     //获取响应内容
//       const obj = window.JSON.parse(xhr.responseText)      //把请求到的字符串输出到div里面,用json API把字符串转为对象
//       name2.textContent = obj.name   
//       age2.textContent = obj.age
//     }
//     xhr.onerror = () => {               //监听——失败
//       console.log('请求失败')
//     }
//     xhr.send("name=frank&age=18")         //发送请求
//   })
// `)
// 以下用到AJAX更详细代码,标准的
// response.write(`
//   const btn = document.querySelector('#btn')
//   btn.addEventListener('click', () => {
//     const xhr = new XMLHttpRequest()
//     xhr.open('GET', '/data')
//     xhr.onreadystatechange = () => {
//       if (xhr.readyState === 4) {
//         if (xhr.status >= 200 && xhr.status < 300) {
//           console.log('请求成功')
//           console.log(xhr.responseText)     //获取响应内容
//           const obj = window.JSON.parse(xhr.responseText)      //把请求到的字符串输出到div里面,用json API把字符串转为对象
//           name2.textContent = obj.name   
//           age2.textContent = obj.age
//         } else if(xhr.status >= 400) {
//           console.log('请求失败')
//         }
//       }
//     }
//     xhr.send("name=frank&age=18")         //发送请求
//   })
// `)
// AJAX API代码太难记了,要求封装
// 封装AJAX,这里使用闭包
response.write(`
  const ajax = (method, url, options) => {
    const {data, success, fail} = options
    const xhr = new XMLHttpRequest()  //构造一个请求实例
    xhr.open(method, url)  //配置请求
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          const type = xhr.getResponseHeader('content-type')
          if(type.startsWith('application/json') || type.startsWith('text/json')){
            success(JSON.parse(xhr.responseText), xhr)
          } else {
            success(xhr.responseText, xhr)
          }
        } else if (xhr.status >= 400) {
          fail(xhr)
        }
      }
    }
    xhr.send(data)   //发送请求
    return {
      abort: () => {xhr.abort()}   //中断
    }
  }
  const btn = document.querySelector('#btn')
  btn.addEventListener('click', () => {
    const api = ajax('GET', '/data', {
      success:(data, xhr)=>{console.log('成功',data, xhr.status)}, 
      fail:(xhr)=>{console.log('失败',xhr.status)}
    })
    setTimeout(() => {api.abort()}, 3000)
  })
`)


response.end()

} else if (path === '/data') { response.statusCode = 200 response.setHeader('Content-Type', 'application/json;charset=utf-8') // 符合 JSON 语法的字符串 response.write({ "name": "张三", "age": 18 }) response.end() } else { response.statusCode = 404 response.setHeader('Content-Type', 'text/html;charset=utf-8') response.write(你输入的路径不存在对应的内容) response.end() }`

AJAX的优缺点:优:可以请求任意内容、不用刷新页面 缺:代码难记,使用别人的封装(JQ/axios)、不能跨域