2022.6.16
eval
:目前很少使用,有安全风险
eval使用方法:
var str = "console.log('hello')"
eval(str)
eval进行json解析:注意加括号
var str = '{"name":"Charles","age":22}'
var obj = eval("(" + str + ")")
console.log(obj)
JSON.parse()
:推荐使用
var str = '{"name":"Charles","age":22}'
var obj = JSON.prase(str)
console.log(obj)
JSON.parse进行默认处理
function fun(name, value){
console.log(name + ":" + value)
return value;
}
var str = '{"name":"Charles","age":22}'
var obj = JSON.prase(str, fun)
JSON.stringify(value[, replacer[, space]])
value: 必须参数,被转换的js值
replacer: 可以省略,可以是函数或数组
space:可以省略,为了排版、方便阅读。可以在JSON字符串中添加空白或制表符
var obj = {
"name": "Charles Shan",
"age": 22,
"a": undefined,
"b": function(){},
"c": [function(){}]
}
var jsonStr = JSON.stringify(obj)
console.log(jsonStr)
// Print: {"name":"Charles","age":22,"c":[null]}
replacer用法(函数)
var obj = {
"name": "Charles Shan",
"age": -1
}
function fun(name,value){
if(name=="age" && value<0)
value = 0
return value
}
var jsonStr = JSON.stringify(obj,fun)
replace用法(数组)
var obj = {
"a":1,
"c":3,
"b":2,
"d":4
}
var jsonStr = JSON.stringify(obj,["a","b","c"])
console.log(jsonStr)
// Print: {"a":1,"b":2,"c":3}
space用法
var obj = {
"a":1,
"c":3,
"b":2,
"d":4
}
var jsonStr = JSON.stringify(obj,["a","b","c"], "--")
console.log(jsonStr)
// Print: {--"a":1,--"b":2,--"c":3}
// 常用方法,添加制表符
var jsonStr = JSON.stringify(obj,["a","b","c"], "\t")
console.log(jsonStr)
//{
// "a":1,
// "b":2,
// "c":3
//}
function CreatXHR(){
if(window.XMLHttpRequest){
// IE7++, Chrome, Firefox
return new XMLHttpRequest()
}else{
// IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP")
}
}
var xmlhttp = CreatXHR()
xmlhttp.open("GET","test.json",true)//true代表异步请求
xmlhttp.send()
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var jsonStr = xmlhttp.responseTest
console.log(jsonStr)
var obj = JSON.parse(jsonStr)
}
}
readyState:
status:是响应码