js遍历json数据

先看看json返回的数据结构:

技术分享

技术分享

我需要遍历取出bookreno   与  title  加载到页面容器中去

首先我要取到 recommendedBookList  字典结构数据,然后遍历反射到相应对象的属性

主方法这样写:

 $(d.recommendedBookList).each(function(index,item){ 

//index指下标 
//item指代对应元素内容

//this指代每一个元素对象 

var bookno= item.bookrecno;
var title = item.title;

        });

也可这样:

$.each(d.recommendedBookList, function (index, item) {
//index指下标
//item指代对应元素内容

//this指代每一个元素对象 

var bookno= item.bookrecno;
var title = item.title;
});

 

具体代码如下:

                <div class="con_pic  picMarquee-left">
                    <div class="bd">
                            <ul class="picList">
                               
                            </ul>
                    </div>
                </div>
                <script type="text/javascript">
                    //var a=1;
                    //var b=10;                  
                    $.ajax({
                        type: "get",
                        dataType: "json",                        
                        //data: "page="+a+"&rows="+b+"&return_fmt=" + encodeURIComponent("json"),
                        data: "page=1&rows=12&return_fmt=" + encodeURIComponent("json"),
                        url: "/interface/BookData.cshtml",
                        error: function (XmlHttpRequest, textStatus, errorThrown) { alert(XmlHttpRequest.responseText);},
                        success: function (d) {
                            var bkinfo = "";
                            $.each(d.recommendedBookList, function (index, item) {
                                //index指下标 
                                //item指代对应元素内容                                
                                //debugger
                               var bookno= item.bookrecno;
                               var title = item.title;
                               var bkurl = "http://202.121.31.35/webopac/book/" + bookno;
                               var bkimg = "http://202.121.31.35/webopac/bscover/" + bookno;
                               var bkli = "<li><div class=‘pic‘><a href=‘" + bkurl + "‘ target=‘_blank‘ title=‘" + title + "‘><img src=‘" + bkimg + "‘ /></a></div><p class=‘title‘><a href=‘" + bkurl + "‘ target=‘_blank‘ title=‘" + title + "‘>" +title.substr(0,5) + "</a></p></li>";
                               bkinfo += bkli;
                            });   
                      
                            $(".picList").html(bkinfo);
                            jQuery(".picMarquee-left").slide({ mainCell: ".bd ul", autoPlay: true, effect: "leftMarquee", vis: 8, interTime: 50 });
                        }
                    });
                </script>

ajax调用页面:

@using ChaoXingPMS.DBEntity;
@using System.Text;

@{ 

    var page = HttpContext.Current.Request["page"];
    var rows = HttpContext.Current.Request["rows"];
    var return_fmt = HttpContext.Current.Request["return_fmt"];

    //string _posturl = "http://202.121.31.35/webopac/recommended?page=1&rows=10&return_fmt=json";
    string _posturl = "http://202.121.31.35/webopac/recommended?page=" + page + "&rows=" + rows + "&return_fmt=" + return_fmt;
        
        //通过WebRequest对象获取返回值
        WebClient client = new WebClient();
        client.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
        client.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
        client.Headers["HOST"] = "opac.lib.shcc.edu.cn";
        client.Headers["Accept-Language"] = "zh-CN,zh;q=0.8";
        client.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36";
        client.Dispose();
        string strLine = "", temp;
        try
        {
            Stream stream = client.OpenRead(_posturl);
            StreamReader sr = new StreamReader(stream);
            while ((temp = sr.ReadLine()) != null)
            {
                strLine += temp;
            }
            stream.Close();
            sr.Close();
        }
        catch (Exception e)
        {
        }     
        Response.Write(strLine);    
}

 

另附参考博客:

http://www.cnblogs.com/lovenan/archive/2012/12/07/2807190.html

JS 循环遍历JSON数据

JSON数据如:{"options":"[{\"text\":\"王家湾\",\"value\":\"9\"},{\"text\":\"李家湾\",\"valu 
e\":\"10\"},{\"text\":\"邵家湾\",\"value\":\"13\"}]"} 

用js可以写成: JSON数据如:{"options":"[{\"text\":\"王家湾\",\"value\":\"9\"},{\"text\":\"李家湾\",\"valu
e\":\"10\"},{\"text\":\"邵家湾\",\"value\":\"13\"}]"}

用js可以写成:

view plaincopy to clipboardprint?
01.var data=[{name:"a",age:12},{name:"b",age:11},{name:"c",age:13},{name:"d",age:14}];   
02.      for(var o in data){   
03.        alert(o);   
04.        alert(data[o]);   
05.        alert("text:"+data[o].name+" value:"+data[o].age );   
06.      }  
var data=[{name:"a",age:12},{name:"b",age:11},{name:"c",age:13},{name:"d",age:14}];
   for(var o in data){
    alert(o);
  alert(data[o]);
    alert("text:"+data[o].name+" value:"+data[o].age );
   }

或是

view plaincopy to clipboardprint?
01.<script type="text/javascript">   
02.function text(){   
03.  var json = {"options":"[{\"text\":\"王家湾\",\"value\":\"9\"},{\"text\":\"李家湾\",\"value\":\"10\"},{\"text\":\"邵家湾\",\"value\":\"13\"}]"}    
04.  json = eval(json.options)   
05.  for(var i=0; i<json.length; i++)   
06.  {   
07.     alert(json[i].text+" " + json[i].value)   
08.  }   
09.}   
10.</script> 

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/songylwq/archive/2010/12/01/6047609.aspx

view plaincopy to clipboardprint? 
01.var data=[{name:"a",age:12},{name:"b",age:11},{name:"c",age:13},{name:"d",age:14}];   
02.      for(var o in data){   
03.        alert(o);   
04.        alert(data[o]);   
05.        alert("text:"+data[o].name+" value:"+data[o].age );   
06.      }  
var data=[{name:"a",age:12},{name:"b",age:11},{name:"c",age:13},{name:"d",age:14}]; 
  for(var o in data){ 
  alert(o); 
alert(data[o]); 
  alert("text:"+data[o].name+" value:"+data[o].age ); 
  } 

或是 

view plaincopy to clipboardprint? 
01.<script type="text/javascript">   
02.function text(){   
03.  var json = {"options":"[{\"text\":\"王家湾\",\"value\":\"9\"},{\"text\":\"李家湾\",\"value\":\"10\"},{\"text\":\"邵家湾\",\"value\":\"13\"}]"}    
04.  json = eval(json.options)   
05.  for(var i=0; i<json.length; i++)   
06.  {   
07.     alert(json[i].text+" " + json[i].value)   
08.  }   
09.}   
10.</script> 

 

    window.onload = function () {
        var jsJosn1 = ‘<%=Jsonstr%>‘;   //从后台获取json商品字符串
        var obj = eval(‘(‘ + jsJosn1 + ‘)‘);  //将字符串转为json对象
        obj = eval(obj.TableInfo);
        //循环商品
        for (var i = 0; i < obj.length; i++) {
            //alert(obj[i].BaseProductName + " " + obj[i].BaseProductNO + " " + obj[i].OrderPrice + " " + obj[i].OrderAmount + " " + obj[i].Unit + " " + obj[i].BPID);
            AddProduct(obj[i].BaseProductName, obj[i].BaseProductNO, obj[i].OrderPrice, obj[i].Unit, obj[i].OrderAmount, obj[i].BPID);
        }
    }

 
http://www.cnblogs.com/Fooo/p/3576367.html
 var obj = {"status":1,"bkmsg":"\u6210\u529f","bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u6dfb\u52a0\u8bb0\u5f55"]}{"status":1,"bkmsg":"\u6210\u529f","bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u6dfb\u52a0\u8bb0\u5f55"]},{"status":1,"bkmsg":"\u6210\u529f","bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u4ec0\u4e48\u4e5f\u6ca1\u6709"]}
ajax请求:
$.ajax({ 
        url: /path/to/file, 
        type: GET, 
        dataType: json, 
        data: {param1: value1}, 
        success: function (obj){  
            //遍历obj 
        } 
    })

返回的内容在success的函数里面,所有的遍历操作都是在这里面操作的: 

for循环:

var obj = { 
        "status":1, 
        "bkmsg":"\u6210\u529f", 
        "bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u6dfb\u52a0\u8bb0\u5f55"] 
    } 
   // console.log(obj.length); 
    if (obj.status == 1) { 
        for (var i = 0; i < obj.bkdata.length; i++) { 
            console.log(obj.bkdata[i]); 
        }; 
    }else{ 
        alert("数据有误~"); 
    };

for in 循环:

//for in循环 
    for(x in obj.bkdata){ 
        //x表示是下标,来指定变量,指定的变量可以是数组元素,也可以是对象的属性。 
        console.log(obj.bkdata[x]); 
    }  

//元素 each方法

if (obj.status == 1) { 
        $(obj.bkdata).each(function(index,item){ 
            //index指下标 
            //item指代对应元素内容 
            //this指代每一个元素对象 
            //console.log(obj.bkdata[index]); 
            console.log(item); 
            //console.log($(this)); 
        }); 
    }else{ 
        alert("数据有误~"); 
    };

//jquery each方法

$.each( obj.bkdata, function(index,item){ 
        console.log(item); 
    });  

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。