JSON 不是编程语言 是标记语言 跟 HTML、XML、Markdown 一样,用来展示数据
支持的数据类型
- string-只支持双引号,不支持单引号和无引号
- number-支持科学记数法
- bool-true 和 false
- null-没有 undefined
- obiect
- array
就这六种,注意跟 JS 的七种数据类型区别开来不支持函数,不支持变量(所以也不支持引用)
用AJAX加载 JSON
getJSON.onclick = ()=>{const request = new XMLHttpRequest()request.open("get","/5.json")request.onreadystatechange = ()=>{if(request.readyState === 4 && request.status === 200){console.log(request.response)const object = JSON.parse(request.response)//变对象myName.textContent = object.nameconsole.log(object)}}request.send()}
window.JSON
JSON. parse
将符合 JSON 语法的字符串转换成 JS 对应类型的数据
JSON 字符串=> JS 数据
由于 JSON 只有六种类型,所以转成的数据也只有 6 种
如果不符合 JSON 语法,则直接抛出一个 Error 对象
一半用 try catch 捕获错误
JSON. stringify
是 JSON.parse 的逆运算
JS 数据=> JSON 字符串
由于 JS 的数据类型比 JSON 多,所以不一定能成功
如果失败,就抛出一个 Error 对象
加载分页
let n = 1getPage.onclick = () => {const request = new XMLHttpRequest()request.open('GET', `/page${n+1}`)request.onreadystatechange = () => {if (request.readyState === 4 && request.status === 200) {const array = JSON.parse(request.response)array.forEach(item => {const li = document.createElement("li")li.textContent = item.idxxx.appendChild(li)})n += 1}}request.send()}
