jquery
  • jsonp
  • 2013-04-04 58 views 0 likes 
    0

    我想从json数组中读取id和名称。我写了下面的代码,但是当我尝试使用parseJSON方法读取id时,它给了我未定义的代码。任何人都可以告诉我如何阅读json数据。以下是我写的代码:使用jquery读取json数据

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
    <script type='text/javascript'> 
    $(document).ready(function() { 
    // $("#request_content").click(function(){ 
        $('#time').html(new Date); 
        $('#status').html(''); 
        $('#content').html(''); 
        var id = ''; 
        $.ajax({ 
         cache: false, 
         url: $('#xhr_url').val() 
        }).done(function(data, textStatus, jqXHR) { 
        //alert(data);  
         $('#status').html(textStatus); 
         $('#content').html(JSON.stringify(data)); 
    
        var jsonp = JSON.stringify(data); 
        var obj = $.parseJSON(jsonp); 
         $.each(obj, function() { 
         //alert("hi"); 
          id += this['Id'] + "<br/>"; 
          $('#content').html(id); 
         }); 
         //$('#content').html(lang); 
        }).fail(function(jqXHR, textStatus) { 
         $('#status').html(textStatus);  
         $('#content').html('(failed)'); 
        }) 
    // }); 
    }); 
    </script> 
    <body> 
        <input id='xhr_url' style='width:600px;' type='text' value='http://t2json.tgoservices.com/818746/PrinterManufacturers'/> 
    
        <button id='request_content'>Request content</button> 
        <fieldset><legend>Time:</legend> 
        <div id='time'></div> 
        </fieldset> 
        <fieldset><legend>Status:</legend> 
        <div id='status'></div> 
        </fieldset> 
        <fieldset><legend>Content:</legend> 
    
        <div id='content'></div> 
        </fieldset> 
    </body> 
    

    请让我知道问题是什么。

    +0

    向我们显示JSON字符串。为什么你要连续两行对数据进行串联和解析? – freakish 2013-04-04 07:41:10

    回答

    0

    你的每一个功能更改如下

    var id = ""; 
    $.each(data.T2Json.PrinterManufacturers.Items, function() { 
        id += this.Id + "<br/>"; 
        console.log(this.Id); 
    }); 
    

    这是一个完整的工作示例http://jsfiddle.net/mayooresan/4eU4X/

    这里您的服务返回JavaScript对象而不是JSON字符串。所以如果你用JSON.parse()解析它会给你错误。

    0

    替换这个代码行:

    var jsonp = JSON.stringify(data); 
    var obj = $.parseJSON(jsonp); 
        $.each(obj, function() { 
        //alert("hi"); 
         id += this['Id'] + "<br/>"; 
         $('#content').html(id); 
        }); 
    

    有了这个:

    $.each(data, function(idx, value){ 
        var items = value.PrinterManufacturers.Items; 
        for(var a = 0; a < items.length; a++) { 
         id += items[a].Id + '<br>'; 
        } 
        $('#content').html(id); 
    }); 
    
    相关问题