这似乎是一个常见问题,我找不到明确的答案。jQuery显示AJAX/API数据两次
我正在使用API通过AJAX调用来拉取JSON数据。我返回的数据在控制台和DOM中显示两次。
$(document).ready(function() {
$('.btn').click(function(){
var $dataHere = $('.dataHere');
var company = "square205";
var key = "xxx";
var action = "time_entries.json?callback=?";
console.debug()
$.ajax({
url: 'https://' + company + '.teamwork.com/' + action,
headers: {"Authorization": "BASIC " + window.btoa(key + ":xxx")},
dataType: 'JSON',
// billableType: "billable",
page: "1",
success: function(data) {
$.each(data, function(i, projects) {
$dataHere.append('<div class="item"><p>Project name: ' + data["time-entries"][0]["project-name"] + '</p>' +'<p>Task name: ' + data["time-entries"][0]["todo-item-name"] + '</p>' + '<p>Hours: ' + data["time-entries"][0]["hours"] + '</p></div>');
console.log(data);
});
}
});
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<title>S205 TIME LORD</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="main.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<span class="timeLordTitle">
<img class="logo" src="http://square205.com/wp-content/themes/square205/images/logo-white.png" alt=""><strong> TIME LORD</strong></span>
<div class="btn">
<div class="hexagon">
<div class="hexTop"></div>
<div class="hexBottom"></div>
</div>
</div>
</br>
<div class="dataHere"></div>
</body>
</html>
因为您正在使用'$ .each'。循环遍历数据对象的每个属性。如果该对象中有多个属性,它将被多次调用。 –
您已经使用过data [“time-entries”] [0],** 0 **,它应该是可变的,并且$ .each遍历每个DOM元素。所以,如果你有多个元素,它会多次打印输出。 [jquery each](https://api.jquery.com/each/) – singhpradeep
根据[mcve]提供样本数据和预期结果 – charlietfl