JSon In Asp.net(II)

以前文章:JSon In Code 之 Asp.net ( I )

首先来看看一段Html代码

Html文件:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script>
   $(function(){
        $('#send').click(function() {
             $.getJSON('test.json', function(data) {
                 $('#resText').empty();
	        var html = '';
	        $.each( data  , function(commentIndex, comment) {
		 html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' +
                       comment['content'] + '</p></div>';
		})
	        $('#resText').html(html);
            })
       })
   })
   </script>
</head>
<body>
     <input type="button" id="send" value="加载"/>
     <div id="resText" > </div>
</body>

test.json文件

[
  {
    "username": "张三",
    "content": "沙发."
  },
  {
    "username": "李四",
    "content": "板凳."
  },
  {
    "username": "王五",
    "content": "地板."
  }
]

以上的代码,我想对其扩展

需求:

1.数据源进行扩展

2.应用到Asp.net WebApplication上面

方案:

数据源进行扩展

我希望在test.json中定义不同的JSON数据集合,如何做?

首先定义多集合的JSON数据集合

test.json文件

{
  user:[  {  "username": "王五", "content": "地板." } ],  
  user1:[ { "username": "张三1","content": "沙发1." } ]
}

然后JQuery代码相应改为:

            $.getJSON('test.json', function(data) {
                 $('#resText').empty();
	        var html = '';
	        $.each( data.user, function(commentIndex, comment) {...})
	        $('#resText').html(html);
            })

 


应用到Asp.net WebApplication上面

首先解决路径问题,因为getJSON(url,params,callback)--第一参数是url的

如果以定义为如下的方式

       $.getJSON('test.json', function(data){});

是不行的!

如果用浏览器直接浏览test.json的话,如下图示,报错

image

 

所以要搞定这个,我们要去定义一个MIME类型

image

        

image

image

好了,浏览JSON文件没有问题了.

JQuery代码定义如下:

            $('#send').click(function() {
                $.getJSON('JSonDataFiles/test.json', function(data) {
                    $('#resText').empty();
                    var html = '';
                    $.each(data.user1, function(commentIndex, comment) {
                           。。。
                    })
                    $('#resText').html(html);
                })
            })

完了。

posted @ 2009-12-08 13:39  RicoRui  阅读(516)  评论(1编辑  收藏  举报