从JSON URL检索数据

时间:2018-11-20 11:05:35

标签: javascript json

这些是我的JavaScript,CSS和HTML代码。我无法找到经纬度的Google API。它始终显示空白页面,没有来自网址的任何数据。

$.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);
    }
});

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/table.js"></script>
  </head>
<body>
<table id="personDataTable">

    <tr>
        <th>Lat</th>
        <th>Lng</th>
        
    </tr>
</table>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

首先,根据经验,切勿发布您的API密钥。 API密钥是AJAX请求中与key参数关联的值。

第二,您既未提供失败回调,也未验证从上述请求返回的数据(在成功回调中)。

我强烈建议您将这些更改添加到代码中,并检查您看到的内容(带有一些日志)。

我想到的一个问题是CORS,但是我不确定,因为我没有足够的信息来了解从何处运行此代码。

相关问题