一、json序列化和解析
<script>
var person = {
name: "tf",
age: 22,
body: {
height: 172,
weight: 60
}
}
var personJson = JSON.stringify(person);
console.log(personJson);
var personJson2 = JSON.stringify(person, function (key, value) {
switch(key){
case "height":
return value + "cm";
case "weight":
return value + "kg";
default: // 必须要有
return value;
}
})
console.log(personJson2);
var personJson3 = JSON.stringify(person, ["name", "age"], 4);
console.log(personJson3);
var personObj = JSON.parse(personJson2);
console.log(personObj);
</script>
二、Ajax请求
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
// console.log(xhr.responseText);
}else {
console.log("err " + xhr.status);
}
xhr = null;
}
}
xhr.open("get", "data.json", true);
xhr.send(null);
var xhr2 = new XMLHttpRequest();
xhr2.onreadystatechange = function () {
if(xhr2.readyState == 4){
if(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status == 304){
console.log(xhr2.responseText);
}else {
console.log("err " + xhr2.status);
}
xhr2 = null;
}
}
xhr2.onloadstart = function () {
console.log("receive the first byte.");
}
xhr2.onprogress = function () {
console.log("receiving the data.");
}
xhr2.onload = function () {
console.log("receive all data.");
}
xhr2.onloadend = function () {
console.log("complete!")
}
var myData = {
"name": "zs"
}
var data = new FormData(myData);
xhr2.open("post", "data.json");
xhr2.send(data);
</script>
三、jsonp跨域
<script>
var scr = document.createElement("script");
scr.src = "https://suggest.taobao.com/sug?code=utf-8&q=%E5%8D%AB%E8%A1%A3&callback=cb";
document.body.insertBefore(scr, document.body.firstChild);
function cb(response) {
console.log(response);
}
</script>
即通过script标签的src进行跨域访问接口,src参数包含一个回调函数(上为cb),接受参数为响应体。