JSON 不是编程语言 是标记语言 跟 HTML、XML、Markdown 一样,用来展示数据

支持的数据类型

  • string-只支持双引号,不支持单引号和无引号
  • number-支持科学记数法
  • bool-true 和 false
  • null-没有 undefined
  • obiect
  • array

就这六种,注意跟 JS 的七种数据类型区别开来不支持函数不支持变量(所以也不支持引用

用AJAX加载 JSON

  1. getJSON.onclick = ()=>{
  2. const request = new XMLHttpRequest()
  3. request.open("get","/5.json")
  4. request.onreadystatechange = ()=>{
  5. if(request.readyState === 4 && request.status === 200){
  6. console.log(request.response)
  7. const object = JSON.parse(request.response)//变对象
  8. myName.textContent = object.name
  9. console.log(object)
  10. }
  11. }
  12. request.send()
  13. }

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 对象

加载分页

  1. let n = 1
  2. getPage.onclick = () => {
  3. const request = new XMLHttpRequest()
  4. request.open('GET', `/page${n+1}`)
  5. request.onreadystatechange = () => {
  6. if (request.readyState === 4 && request.status === 200) {
  7. const array = JSON.parse(request.response)
  8. array.forEach(item => {
  9. const li = document.createElement("li")
  10. li.textContent = item.id
  11. xxx.appendChild(li)
  12. })
  13. n += 1
  14. }
  15. }
  16. request.send()
  17. }