简体   繁体   中英

How do I access this json object inside this api?

I'm trying to access an item in an api so I can start getting data from the json file, but I can't seem to get anything to work. I'm unable to log any of the data I'm trying to access to the console.

我正在尝试访问的JSON图片

  $(function() {

  $.ajax({
    type: 'GET',
    url: "xxx",
    dataType: 'json',
    success: function(data) {
      return console.log('success', data);
      return console.log(data[0].id);
    },
    beforeSend: function(xhr, settings) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
    }
  });
});

It isn't working because you are returning before the second console.log . the return statement is used to exit a function at that line and return the value of the rest of the line. You are returning then trying to do something after the return which actually is never ran.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

Remove the return statements and it should work.

$.ajax({
    type: 'GET',
    url: "xxx",
    dataType: 'json',
    success: function(data) {
      console.log('success', data);
      console.log(data[0].id);
    },
    beforeSend: function(xhr, settings) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
    }
});

1) You have a problem with returning before the Id is logged to the console, as you are returning it before your you logging your Id, a return statement ends the function execution. so removing the return will do the work

2) you don't really need to console.log() everything you can just put a ' debugger; ' instead of return and you can reload the page with an open console window, it will pause the code execution at the debugger; and you can hover on the ' data ' being received in the success function to see all the data being received on a successful AJAX call. hope this helps

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