简体   繁体   English

如何在此api中访问此json对象?

[英]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. 我正在尝试访问api中的项目,这样我就可以开始从json文件中获取数据了,但是似乎什么也没用。 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 . 它不起作用,因为您要在第二个console.log之前返回。 the return statement is used to exit a function at that line and return the value of the rest of the line. return语句用于在该行退出函数并返回其余行的值。 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

Remove the return statements and it should work. 删除return语句,它应该可以工作。

$.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. 1)在将ID记录到控制台之前,您有返回问题,因为在记录ID之前要返回它,所以return语句将结束函数执行。 so removing the return will do the work 所以去掉退货就可以了

2) you don't really need to console.log() everything you can just put a ' debugger; 2)您实际上不需要console.log()只需放置一个调试器即可; ' 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. 您可以将鼠标悬停在成功函数中正在接收的“ 数据 ”上,以查看在成功的AJAX调用中正在接收的所有数据。 hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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