批改状态:合格
老师批语:
const player={account:"376220510",name:"烈火点烟",password:"6350187",sex:"男",phone:"18959261401",};jsonStr = JSON.stringify(player);console.log(jsonStr);
可以通过回调函数选择返回的json格式,也可以选择不返回某些内容,例如下列代码
const player={account:"376220510",name:"烈火点烟",password:"6350187",sex:"男",phone:"18959261401",};jsonStr = JSON.stringify(player,(key, value) => {switch (key) {case "sex":return value === "男" ? "man" : "woman";case "phone":return undefined;default:return value;}});console.log(jsonStr);
上述代码执行结果中,不返回phone属性,且将sex属性值修改成man返回
传统XHR创建一个get或者post请求需要以下步骤
const xhr = new XMLHttpRequest();xhr.responseType = "json";let url = "http://website.io/users.php";url = "http://website.io/users.php?id=100";xhr.open("GET", url, true);xhr.onload = () => {console.log(xhr.response);render(xhr.response, btn);};xhr.onerror = () => console.log("Error");xhr.send(null);
fetch请求基于 promise, 返回一个Promise对象
let url = "http://website.io/users.php";url = "http://website.io/users.php?id=2";fetch(url).then(response => response.json()).then(json => {console.log(json);render(json, btn);}).catch(err => console.log("Fetch Error", err));
async function getUser(btn) {let url = "http://website.io/users.php";url = "http://website.io/users.php?id=3";const response = await fetch(url);const result = await response.json();console.log(result);render(result, btn);}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号