初识 AJAX

142 阅读1分钟

简介

AJAX ( Async JavaScript And XML)意思是: 异步的 JavaScript 和 XML。它是浏览器上的功能。浏览器可以发请求,收响应。浏览器在 window 上加了一个 XMLHttpRequest 全局函数,用这个构造函数可以构造出一个对象。JS 通过它实现发请求,收响应。

  • window.XMLHttpRequest可以构造出一个对象。该对象可发起 HTTP 请求,可以通过监听其 readystate 的变化获得响应。

使用方法

用 JS 发起一个AJAX请求一共 4 步。

  • 1.创建一个 XMLHTTPRequest 对象
const request = new XMLHttpRequest()
  • 2.调用对象的 open 方法 (设置请求参数)
    • 用两个参数。第一个参数是选择用哪个请求(get/post);第二个参数是URL
request.open('GET', '/style.css')
  • 3.监听对象的 onreadystatechange 事件(监听 readystate 的变化)
    • 在事件处理函数里操作文件内容
request.onreadystatechange = () => {
  if (request.readyState === 4 && request.status >= 200 && request.status < 300) {
     console.log(request.readyState)
  } 
}

// request.readyState === 4 表示下载完成(注意:并不确定下载完成的是成功的路径还是失败的,需要在进行判断)
//只读属性 XMLHttpRequest.status 返回了 XMLHttpRequest 响应中的数字状态码。status 200-299 代表一个成功的请求。(如果服务器响应中没有明确指定 status 码,默认为 200
  • 4.调用对象的 send 方法 - 发送请求
request.send()
  • 注意:请求在不同阶段有不同的readyState
阶段readyState
const request = new XMLHttpRequest()0
request.open()1
request.send()2
第一个响应信息出现在浏览器3
所有响应下载完成4

练习代码:

  • 代码链接:github.com/coolkechang…
  • 简介
    • 使用 server.js 作为练习用的服务器(FrankFang/nodejs-test (github.com)
    • 用 AJAX 加载 CSS (代替<link rel=stylesheet href="1.css"/>
    • 用 AJAX 加载 JS (代替<script src="2.js"></script>
    • 用 AJAX 加载 HTML
    • 用 AJAX 加载 XML
    • 用 AJAX 加载 JSON
  • 代码片段:

加载 CSS

getCSS.onclick = () => {
    const request = new XMLHttpRequest()//readystate = 0
    request.open('GET', 'style.css')  //readystate = 1
    request.onreadystatechange = () => {
        if (request.readyState === 4) {  //readyState === 4 
            if (request.status >= 200 && request.status < 300) {
                const style = document.createElement('style')  //创建 style 标签
                style.innerHTML = request.response  //填写 style 内容。用 request.response 获取相应内容 
                document.head.appendChild(style)  //将 style 插入到 head 里面
            } else {
                alert('CSS加载失败')
            }
        }
    }
    request.send()  //readystate = 2
}

加载 JS

getJS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET', 'javascript.js')
    request.onreadystatechange = () => {
        console.log(request.readyState)
        if (request.readyState === 4) {
            if (request.status >= 200 && request.status < 300) {
                const javascript = document.createElement('javascript')
                javascript.innerHTML = request.response
                document.head.appendChild(javascript)
            } else {
                alert('JS加载失败')
            }
        }
    }
    request.send()
}

加载 HTML

getHTML.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET', 'html.html')
    request.onreadystatechange = () => {
        console.log(request.readyState)
        if (request.readyState === 4) {
            if (request.status >= 200 && request.status < 300) {
                const div = document.createElement('div')
                div.innerHTML = request.response
                document.body.appendChild(div)
            } else {
                alert('HTML加载失败')
            }
        }
    }
    request.send()
}

加载 XML

getXML.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET', '4.xml')
    request.onreadystatechange = () => {
        if (
            request.readyState === 4 &&
            request.status >= 200 &&
            request.status < 300
        ) {
            const dom = request.responseXML  // request 自带一个属性:responseXML 。这个属性是一个只读值,它返回一个包含请求检索的 HTML 或 XML 的Document。即responseXML会自动的将得到的信息变成一个dom对象。
            const text = dom.getElementsByTagName('warning')[0].textContent  //获取dom中warning标签的文本内容
            console.log(text.trim())
        }
    }
    request.send()
}

加载 JSON

getJSON.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET', '5.json')
    request.onreadystatechange = () => {
        if (
            request.readyState === 4 &&
            request.status >= 200 &&
            request.status < 300
        ) {
            const object = JSON.parse(request.response)  //JSON.parse() 将符合 JSON 语法的字符串转换成 JS 对应类型的数据,(在这里是对象)
            myName.textContent = object.name  //这个可实现我们进入网页时出现“欢迎 xxx”的那个情况
        }
    }
    request.send()
}

JSON

JSON 全称 JavaScript Object Notation (JS对象标记语言)。跟 HTML、XML、Markdown 一样,用来展示数据。

  • 具体介绍:JSON
  • 只支持六种数据类型
    • string - 只支持双引号,不支持单引号和无引号
    • number - 支持科学记数法
    • bool - true 和 false
    • null - 没有 undefined
    • object
    • array
    • 不支持函数,不支持变量(所以也不支持引用)
  • JSON建构于两种结构:
    • “名称/值”对的集合。
      • 不同的语言中,它被理解为对象(object) ,纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
    • 值的有序列表。
      • 在大部分语言中,它被理解为数组(array)。

例如:

{
  "name":"chang",
  "age":18,
  "xxx":null
}
[  {"id":1},  {"id":2},  {"id":3},  {"id":4},  {"id":5}]

window.JSON

  • JSON.parse
    • 将符合 JSON 语法的字符串转换成 JS 对应类型的数据(JSON 字符串 => JS 数据)
    • 由于 JSON 只有六种类型,所以转成的数据也只有6种
    • 如果不符合 JSON 语法,则直接抛出一个 Error 对象
    • 一半用 try catch 捕获错误

image.png

  • JSON.stringify
    • 是 JSON.parse 的逆运算(JS 数据 => JSON 字符串)
    • 由于 JS 的数据类型比 JSON 多,所以不一定能成功。如果失败,就抛出一个 Error 对象。(如果是一个函数会直接忽略)

image.png


资料来源:饥人谷前端体系课程