这似乎是一个我无法找到明确答案的常见问题。
我正在使用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>
答案 0 :(得分:0)
你是硬编码的第0个索引。使用i
代替0
$.each(data, function(i, projects) {
$dataHere.append('<div class="item"><p>Project name: ' + data["time-entries"][i]["project-name"] + '</p>' +'<p>Task name: ' + data["time-entries"][i]["todo-item-name"] + '</p>' + '<p>Hours: ' + data["time-entries"][i]["hours"] + '</p></div>');
});
答案 1 :(得分:0)
您是否尝试取消绑定点击,如下所示?
$( 'BTN ')。解除绑定(' 点击')。点击(函数(){ ...... }
答案 2 :(得分:0)
更新:
我明白了。 API回调JSON数据,返回两个属性:STATUS和在time-entries对象中找到的数据。这意味着循环迭代了可用属性的数量(2)。我通过将代码更改为此行来修复代码,因此它只循环遍历一个属性。
$.each(data["time-entries"], function(i, projects) {...}