简体   繁体   中英

JSON node in jquery, Uncaught TypeError: Cannot read property '0' of undefined

How to read the JSON nodes from below jquery code, currently, I am getting "Uncaught TypeError: Cannot read property '0' of undefined" in the firebug, please let me know what am I doing wrong.

Jquery

$(document).ready(function() {


$('#search_btn_2').click(function(){

var queryValue = $('#search_string_2').val();

$('.my-div').hide();

$.getJSON( "${kb_endpoint_url}",
             { search_query : queryValue } 
         )

.done(function( data ) 
{
console.log("success:"+queryValue+":"+data);

alert(data.docs[0].title);                    

$('.my-div').html('<a href="'+data.docs[0].type+'">'+data.docs[0].title+'</a>'); 

})

.done(function() { console.log("second success"); })

.fail(function() { console.log("error"); })

.always(function() { console.log("finished"); $('.my-div').show(); });                   

});

});

JSON

{
   "response":{
      "start":0,
      "docs":[
         {
            "summary":"image/img1.jpg",
            "id":"17",
            "title":"Varun",
            "votecount":0,
            "_version_":1192256,
            "type":"User"
         }
      ],
      "numFound":1
   },
   "responseHeader":{
      "status":0,
      "QTime":1,
      "params":{
         "indent":"true",
         "q":"varun",
         "wt":"json"
      }
   }
}

data.docs is undefined. Per your JSON structure, you're looking for data.response.docs .

You are getting it wrong, your hierarchy is:

data -> response -> docs

however, you are trying to directly access docs ( data -> docs ), which is wrong.

The docs property belongs to the data.response object, so you need to use data.response.docs[0] instead of data.docs[0] .

In your object there is no property called data.docs that is the reason for the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM