s
json对象的构建
单双引号的使用
转意字符(如/在引号里要转意)
json对象转字符串形式JSON.stringify(o)
string对象转化为json对象,eval的用法(对象声明语句来说,仅仅是执行,并不能返回值)
JSON.stringify(), 将value(Object,Array,String,Number...)序列化为JSON字符串
JSON.parse(), 将JSON数据解析为js原生值
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0" />
<script >
function showPopup() {
window.youyuan.showPopup('{"url":"http:\/\/wap.baidu.com","title":"xxxxxx","layout":{"width":"80%","height":"auto"}}');
}
function createJSONObj() {
var user = {
"url" : "http:\/\/wap.baidu.com",
"title":"xxxxxx",
"layout":{
"width":"80%",
"height":"auto"
},
"test_num" : 20,
"test_arr" : [{
"city" : "beijing",
"postcode" : "222333"
}, {
"city" : "newyork",
"postcode" : "555666"
}]
}
return user;
}
function showJSON() {
var user = createJSONObj();
alert(user.url);
alert(user.title);
alert(user.layout.width);
alert(user.test_arr[0].city);
alert(user.test_arr[0].postcode);
}
function testforeach() {
var json = {
aa : true,
bb : false
};
for (var item in json) {
alert(item);
//结果是 aa,bb, 类型是 string
alert( typeof (item));
alert(eval("json." + item));
//结果是true,true类型是boolean
eval(("json." + item + "=false;"));
//改变json对象的值
}
}
//json对象转字符串形式
function json2str(o) {
//也可以用JSON.stringify(o);
//return JSON.stringify(o);
var arr = [];
var fmt = function(s) {
if ( typeof s == 'object' && s != null)
return json2str(s);
return /^(string|number)$/.test( typeof s) ? "'" + s + "'" : s;
}
for (var i in o)
arr.push("'" + i + "':" + fmt(o[i]));
return '{' + arr.join(',') + '}';
}
//json对象转字符串形式
function testjson2str() {
//假如有两个变量,我要将a转换成字符串,将b转换成JSON对象:
var a={"name":"tom","sex":"男","age":"24"};
var b='{"name":"Mike","sex":"女","age":"29"}';
var aToStr=JSON.stringify(a);
var bToObj=JSON.parse(b);
alert(typeof(aToStr)); //string
alert(aToStr); //string
alert(typeof(bToObj)); //object
alert(JSON.stringify(bToObj)); //object
}
//string对象转化为json对象
function stringToJson(stringValue) {
//// 假设后台发送的json数据为 '{a:2,b:1}' 存储于stringValue中
//var theJsonValue = eval( '(' + stringValue + ')' );
eval("var theJsonValue = " + stringValue);
return theJsonValue;
}
</script>
</head>
<body>
<a href="javascript:void(0)" onclick="showPopup()">弹出页</a>
<a href="javascript:void(0)" onclick="showJSON()">test</a>
<a href="javascript:void(0)" onclick="testforeach()">testforeach</a>
<a href="javascript:void(0)" onclick="testjson2str()">testjson2str</a>
</body>
</html>
eval()的使用(执行全局代码)
转自http://wanyij.blog.51cto.com/46570/43794
<script >
var s='function test(){return 1;}'; //一个函数定义语句
function demo2(){
window.eval(s);//全局
//eval(s);//局部
}
demo2();
alert(test());
</script>
s
s

995

被折叠的 条评论
为什么被折叠?



