Javascript 使用AJAX从API URL解析JSON
我正在尝试使用ajax和“GET”方法从API url显示JSONJavascript 使用AJAX从API URL解析JSON,javascript,jquery,arrays,ajax,Javascript,Jquery,Arrays,Ajax,我正在尝试使用ajax和“GET”方法从API url显示JSON function getLatestComments() { $.ajax({ type: 'GET', url: 'https://***********-API.amazonaws.com/deploymentstage/ride', headers: { Authorization: authToken
function getLatestComments() {
$.ajax({
type: 'GET',
url: 'https://***********-API.amazonaws.com/deploymentstage/ride',
headers: {
Authorization: authToken
},
contentType: 'application/json',
success: function (data) {
var text = $("body").append(JSON.stringify(data.records));
console.log(text);
text.forEach(function(records) {
$('#messages').append ('<p> +comments + </p>')
});
},
error: function(err) {
console.error('Something went wrong: ', err);
}
});
}
您没有正确地在JSON数组上循环
text
包含jQuery对象$(“body”)
,而不是JSON响应中的任何内容
你想要
data.records.forEach(comment => $('#messages').append ('<p>' +comment + '</p>'));
data.records.forEach(comment=>$(“#messages”).append(“”+comment+””);
让我再发布一次我正在尝试的函数。contentType
在GET
请求中不是必需的,因为您没有发送任何内容。什么是comments
?text.forEach()
没有多大意义。您正在遍历$(“body”)
的元素,而不是JSON中的记录。您可能需要的是数据.records.forEach(…)
data.records.forEach(comment => $('#messages').append ('<p>' +comment + '</p>'));