用于在html中获取json数据的循环

时间:2016-05-30 12:42:33

标签: javascript jquery json ajax

在这个通过ajax从url获取的json数据中,我无法通过for循环获取标记的内部元素。如果有单个元素,我能够获取数据数组但是当数组中有多个元素时会出现问题

    <input type="button" value="Get and parse JSON" class="button" />
  <br />
  <span id="results"></span>

  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

  <script>

     //When DOM loaded we attach click event to button
     $(document).ready(function() {

        //after button is clicked we download the data
        $('.button').click(function(){

            //start ajax request
            $.ajax({
                url: "http://www.miamia.co.in/dummy/?json=get_recent_posts",
                //force to handle it as text
                dataType: "text",
                success: function(data) {

                    //data downloaded so we call parseJSON function 
                    //and pass downloaded data
                    var json = $.parseJSON(data);
                    //now json variable contains data in json format
                    //let's display a few items
                    $('#results').html('Count: ' + json.count + '<br />' +
     for(var i=0;i<json.posts[0].tags.length-1;i++)
    {
    '<br /> Post tags id: ' + JSON.stringify(json.posts[0].tags[i].id)+'<br /> Post tags slug: ' + JSON.stringify(json.posts[0].tags[0].slug)  //I'm not been able to fetch the elements of tag through the for loop
    }
    );
                }
            });
        });
    });

0 个答案:

没有答案