這似乎是一個常見問題,我找不到明確的答案。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