后来过来的json,不仅仅是数据模型。还包括一些前台处理的方式。比如json串位
{name:'xxxx', age:'xxxx', value:'xxxx'}
现在想在这里加入一个function的handler,比如
加入handle:function(){alert(1);}这样json里就包括name,age,value,handle,这个handle如何在后台生成json的文本串,前台从后台获得了这个串以后,又该如何来进行相应的解析操作。困惑中.....
{name:'xxxx', age:'xxxx', value:'xxxx'}
现在想在这里加入一个function的handler,比如
加入handle:function(){alert(1);}这样json里就包括name,age,value,handle,这个handle如何在后台生成json的文本串,前台从后台获得了这个串以后,又该如何来进行相应的解析操作。困惑中.....
不过貌似没有好的想法了
不知道楼主这样做是不是在写代码生成工具,如果是的话,可以用freeer简单多了。
json.element("name","李明");
json.element("age","20");
json.element("value","11");
json.element("handler","function(){alert(this.name)}");
//这样生成JSON字符串就可以了前台JSvar data = eval("("+response.responseText+")");//拿到的JSON字符串
var handler = data.handler;
handler();就会弹出"李明"
typeof data.handler == 'function'
var resp = "{name:'bao110908', age:'5', value:'3', handle:function(){alert(1);}}";
var json = eval('(' + resp + ')');
if (json && typeof json.handle == 'function') {
json.handle.call(json);
// or
// json.handle.apply(json);
} var resp = "{name:'bao110908', age:'5', value:'3', handle:function(a, b){alert(a + this.age + b);}}";
var json = eval('(' + resp + ')');
if (json && typeof json.handle == 'function') {
json.handle.call(json, '我今年', '岁');
// or
// json.handle.apply(json, ['我今年', '岁']);
}
}
var str = [];
var k = 0;
for(var n in this) {
if(k++ > 0) str.push(', ');
str.push(n);
str.push(':');
var x = this[n];
if(typeof x == 'object') {
str.push('{');
str.push(this[n].toString());
str.push('}');
} else {
str.push(this[n]);
}
}
return str.join('');
}window.onload = function() {
var resp = "{name:'bao110908', age:'5', value:'3', obj: {x:1,y:2}, handle:function(){alert(1);}}";
var json = eval('(' + resp + ')');
var a = [];
a.push('json.name');
a.push(' ' + json.name); a.push("json['name']");
a.push(' ' + json['name']); // 除了 json.name 之外,还可以这样 :P a.push('json.age');
a.push(' ' + json.age); a.push('json.value');
a.push(' ' + json.value); a.push('json.obj');
a.push(' ' + json.obj); a.push('json.obj.x');
a.push(' ' + json.obj.x); a.push('json.obj.y');
a.push(' ' + json.obj.y); a.push('json.handle');
a.push(' ' + json.handle); a.push('json.toString()');
a.push(' ' + json.toString()); alert(a.join('\n'));
}
</script>