如何从url获取json数据?

时间:2016-05-28 13:10:19

标签: jquery html json ajax

我无法获取json数据的内部元素。 Here's json数据的链接。

这是我的代码:

$(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('Pages:'+ json.pages + '<br />postid: '+json.posts.id);//here I am not able to get the id
             }
        });
    });
 });

1 个答案:

答案 0 :(得分:0)

注意事项:

  1. dataType: "JSON"
  2. 返回的数据是JSON,因此无需将其解析为JSON
  3. 它是data.posts[0].id而不是data.posts.id
  4. 以下演示有效。您可以检查console.log或浏览器的开发人员控制台中返回的json内容。

    $(document).ready(function() {
    
      //after button is clicked we download the data
      $('body').on("click", "#button", function() {
    
        //start ajax request
        $.ajax({
          url: "http://www.miamia.co.in/dummy/?json=get_recent_posts&callback=?",
    
          dataType: "JSON",
          success: function(data) {
            console.log(data);
            //let's display a few items
            $('#results').html('Pages:' + data.pages + '<br />postid: ' + data.posts[0].id); //here I am not able to get the id
          }
        });
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <div id="results">
    
    </div>
    <input id="button" type="button" value="Get posts">

相关问题