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);
}
相关推荐
© 2020 asciim码
人生就是一场修行