javascript - 我的网页无法通过 JSON 请求运行

标签 javascript jquery json html-table

我试图弄清楚是否有办法将 API 结果 (JSON) 获取到 html 表。我尝试的方法没有成功。 我正在尝试从 tfl API 获取 JSON。

这是我目前正在处理的代码片段:

<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<table class="table table-border table-stiped" id="test_table"
<body>


<table>
<script>
$(document).ready(function(){
$.getJSON("https://api.tfl.gov.uk/Journey/JourneyResults/1000012/to/1000172",function(data){
    var test_data = '';
    $.each(data, function(key, value){
      test_data += '<tr>';
      test_data += '<td>'+value.duration+'</td>';
	  test_data += '<td>'+value.arrivalDateTime+'</td>';
	  test_data += '<td>'+value.departureTime+'</td>';
      test_data += '</tr>';
      
    });
    $('#test_table').append(test_data);
  });
  });
</script>
</table>
</body>

最佳答案

在操作JSON之前,尝试理解JSON结构(ajax响应)。 我对代码段进行了一些更改以供引用(工作)

<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<table class="table table-border table-stiped" id="test_table"
<body>


<table>
<script>
$(document).ready(function(){
$.getJSON("https://api.tfl.gov.uk/Journey/JourneyResults/1000012/to/1000172",function(data){
    var test_data = '';
    $.each(data.journeys, function(key, value){
      test_data += '<tr>';
      test_data += '<td>'+value.duration+'</td>';
	  test_data += '<td>'+value.arrivalDateTime+'</td>';
	  test_data += '<td>'+value.startDateTime+'</td>';
      test_data += '</tr>';
      
    });
    $('#test_table').append(test_data);
  });
  });
</script>
</table>

关于javascript - 我的网页无法通过 JSON 请求运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53650667/

相关文章:

javascript - 使用 JavaScript 在浏览器中控制 USB PTZ 摄像头

javascript - jQuery:检测 X 部分后未加载的 iFrame

jquery - 如何在 jquery 中使用循环将 id 添加到 tr

Android GSON反序列化删除空数组

javascript - 在 VSCode 扩展中使用 JavaScript DOM

javascript - 如何使用 pagetoken 谷歌应用程序脚本

jquery - 在 jQuery 中,如何访问克隆的 div 对象中的子 div?

jquery - 将文本附加到类名称的末尾,以表明 jQuery 正在利用这些类

json - 在Kotlin中使用GSON解析JSON

json - 如何使用SED转换JSON格式的数据