我正在使用 Googlebooks API 开发一个项目,但是当我尝试将数据 append 到 DOM 上时,我得到了 [object Object]。
$('button').on('click', function(){
//code below allows you to pick between buttons so that it gives you different results
var x = $(this).data('search');
console.log(x);
//code below pulls the results from the google api key.
var queryURL = ' https://www.googleapis.com/books/v1/volumes?q=+genres'+x+'&api_key=AIzaSyAHjfwSHwLklSKp1lb38metYYW-gtt5tY4&limit=10';
console.log(queryURL);
//code below is acutual api call
$.ajax({url:queryURL,method:'GET'})
.done(function(response){
console.log(response.items[0].volumeInfo);
//to get the results on the page
$('#body').append('<span>'+response.items[0].volumeInfo+'</span>');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="body">
<button>Click Me</button>
</div>
我做错了什么?
最佳答案
您得到[object Object]
的原因是因为您正在尝试将Javascript对象添加到屏幕(显示在控制台中)。
要解决此问题,您必须单独输出每个属性(例如 response.items[0].volumeInfo.title
,它将返回 “古英语、古冰岛语和盎格鲁语的朗文选集-诺曼文学”
)
将整个对象输出为字符串的简单方法可能是使用 JSON.stringify(),但您可能希望通过输出各个属性来更好地格式化结果。请参阅下面的非格式化结果。
$('button').on('click', function(){
//code below allows you to pick between buttons so that it gives you different results
var x = $(this).data('search');
console.log(x);
//code below pulls the results from the google api key.
var queryURL = ' https://www.googleapis.com/books/v1/volumes?q=+genres'+x+'&api_key=AIzaSyAHjfwSHwLklSKp1lb38metYYW-gtt5tY4&limit=10';
console.log(queryURL);
//code below is acutual api call
$.ajax({url:queryURL,method:'GET'})
.done(function(response){
console.log(response.items[0].volumeInfo);
//to get the results on the page
$('#body').append('<span>'+JSON.stringify(response.items[0].volumeInfo)+'</span>');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="body">
<button>Click Me</button>
</div>
还有一些格式:
$('button').on('click', function(){
//code below allows you to pick between buttons so that it gives you different results
var x = $(this).data('search');
console.log(x);
//code below pulls the results from the google api key.
var queryURL = ' https://www.googleapis.com/books/v1/volumes?q=+genres'+x+'&api_key=AIzaSyAHjfwSHwLklSKp1lb38metYYW-gtt5tY4&limit=10';
console.log(queryURL);
//code below is acutual api call
$.ajax({url:queryURL,method:'GET'})
.done(function(response){
console.log(response.items[0].volumeInfo);
//to get the results on the page
$('#body').append(
'<p>Tilte: '+response.items[0].volumeInfo.title+'</p>' +
'<p>Authors: '+response.items[0].volumeInfo.authors.join(", ")+'</p>'
);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="body">
<button>Click Me</button>
</div>
关于javascript - 尝试从 Google Books API append 信息时获取对象 Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59060261/