我尝试运行代码,并且已成功从 url 检索 json,因为返回了警报成功。但是,当我尝试检索数据时,json 文件没有结果。有人可以帮我解决这个问题吗?
$.ajax({
type: "GET",
url: 'https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=YOUR-API-KEY',
dataType: "json",
success: function(data){
drawTable(data);
alert("Success!");
}
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row);
row.append($("<td>" + rowData.lat + "</td>"));
row.append($("<td>" + rowData.lng + "</td>"));
}
table {
border: 2px solid #666;
width: 100%;
}
th {
background: #f8f8f8;
font-weight: bold;
padding: 2px;
}
<!DOCTYPE html>
<html>
<head>
<title>Json to HTML</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="css/table.css">
<script type="text/javascript" src="js/table2.js"></script>
</head>
<body>
<table id="personDataTable">
<tr>
<th>Lat</th>
<th>Lng</th>
</tr>
</table>
</body>
</html>
我已编辑添加了我尝试检索的 json 数据,我不断收到成功连接到网页的信息,但没有检索到任何数据。
{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJa147K9HX3IAR-lwiGIQv9i4",
"types" : [ "amusement_park", "establishment", "point_of_interest" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJzzgyJU--woARcZqceSdQ3dM",
"types" : [ "amusement_park", "establishment", "point_of_interest" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 34.1373841,
"lng" : -117.9220826
},
"southwest" : {
"lat" : 33.8151707,
"lng" : -118.3575585
}
},
最佳答案
正如其他用户评论的那样,您应该首先检查从 api 获取的数据是否正确。表明您已达到该点的警报并不能保证您拥有所需的数据。另一方面,如果您有正确的数据,请考虑此解决方案
根据您尝试在表中绘制的数据结构,我认为它可能是这样的:
[
{
"lat": 123,
"lng": 456,
}, {
"lat": 789,
"lng": -456,
}, {
"lat": 321,
"lng": 956,
}
]
当然会有更多数据,但我想这些是您案例中的相关数据。如果是这种情况,一种方法如下:
const dataset = [
{
lat: 123,
lng: 456,
}, {
lat: 789,
lng: -456,
}, {
lat: 321,
lng: 956,
}
];
function drawTable(dataset) {
const rows = dataset.map(drawRow).join('');
document.querySelector('#root').innerHTML = `
<table>
<thead>
<tr>
<th>Latitude</th>
<th>Longitude</th>
</tr>
</thead>
<tbody>
${rows}
</tbody>
</table>`;
}
function drawRow(data) {
return `<tr>
<td>${data.lat}</td>
<td>${data.lng}</td>
</tr>`;
}
// This call to the function in your example would be within the callback success in your ajax method
drawTable(dataset);
table {
border: 2px solid #666;
width: 100%;
}
th {
background: #f8f8f8;
font-weight: bold;
padding: 2px;
}
<div id="root"></div>
关于javascript - 从url中检索Json成功但表上没有显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53550477/