如何访问API返回的JSON对象并获取其中数据?
Hey there, let's break down why your code isn't working as expected and get it sorted out step by step:
1. The Return Statement Blocking Your Second Log
In your success callback, you’ve got two return console.log(...) lines. The first return immediately exits the function, so the second log (trying to access data[0].id) never runs at all. You don’t need return with console.log—just remove those keywords, and both logs will execute.
2. Mismatched JSON Structure Access
Looking at your JSON screenshot, the top-level response is an object that contains a data property (which is the array you want to work with). Your current code tries data[0].id, which treats the entire response as an array—but it’s not. You need to first access the data array inside the response object.
Corrected Code
Here’s the fixed version of your AJAX call:
$(function() { $.ajax({ type: 'GET', url: "xxx", dataType: 'json', success: function(response) { console.log('success', response); // Access the nested data array first, then get the first item's id console.log(response.data[0].id); }, beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx'); } }); });
Extra Debugging Tips
- Use
console.dir(response)instead ofconsole.logif you want to explore the full structure of the response object interactively in your browser’s dev tools. - To avoid errors if the
dataarray is empty or missing, add a quick check:if (response.data && response.data.length > 0) { console.log(response.data[0].id); } else { console.log('No data found in the response'); }
内容的提问来源于stack exchange,提问作者branhillsdesign

