代码改变世界

c#生成json数据 JavaScript对json数据处理

2009-09-11 15:25  zhaoyang  阅读(698)  评论(0编辑  收藏  举报
c#主要代码如下



if (dt.Rows.Count > 0)
{
StringBuilder cinema_sb = new StringBuilder("{\"filmlist\":[");
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i == dt.Rows.Count - 1)
{
cinema_sb.Append("{\"filmname\":\"" + dt.Rows[i]["filmname"].ToString() + "\",\"filminfoid\":" + dt.Rows[i]["filminfoid"].ToString() + "}");
}
else
{
cinema_sb.Append("{\"filmname\":\"" + dt.Rows[i]["filmname"].ToString() + "\",\"filminfoid\":" + dt.Rows[i]["filminfoid"].ToString() + "},");
}
}
cinema_sb.Append("]}");
Response.Write(cinema_sb.ToString());
}
else
{
Response.Write("暂无数据");
}

改程序返回的json数据格式如下:



{"filmlist":[{"filmname":" 哆啦A梦","filminfoid":91797},{"filmname":"《金刚》","filminfoid":44},{"filmname":"《首都塔那那利佛——马达加斯加游记之一》","filminfoid":66990},{"filmname":"《玩命快递》","filminfoid":87},{"filmname":"《我的父亲母亲》","filminfoid":88416},{"filmname":"《月亮》","filminfoid":90949},{"filmname":"《战鸽总动员》","filminfoid":46},{"filmname":"哈利.波特与凤凰社","filminfoid":91771},{"filmname":"哈利·波特与凤凰社","filminfoid":64184},{"filmname":"黄金甲","filminfoid":91776},{"filmname":"精舞门","filminfoid":91783},{"filmname":"情癫大圣","filminfoid":91782},{"filmname":"水妖","filminfoid":91773}]}





前台对这些数据进行处理主要代码如下所示:



$.ajax({type:'POST',url:cs3,data:'',success:function(data){
if(data=="暂无数据")
{
var jsontemp = eval('('+data+')')
var contentstr = "<ul>"
for(i=0;i<jsontemp.filmlist.length;i++)
{
contentstr = contentstr+"<li>"
contentstr = contentstr+jsontemp.filmlist[i].filmname
contentstr = contentstr+"</li>"
}
contentstr = contentstr+"<ul>"



说明:前台处理json数据时以jquery为基础的,所以前台页面必须引入jquery的js文件,jquery的$.ajax()方法获得数据然后进行相关处理