gpt4 book ai didi

javascript - 使用 jquery 为任何字段在 javascript 中从 json 创建表

转载 作者:行者123 更新时间:2023-11-29 15:34:29 26 4
gpt4 key购买 nike

到目前为止,我可以查看 json 响应。现在我想将它们转换为表格。我正在使用以下代码来解析有关城市天气的数据。我正在尝试使用以下代码。

    <!DOCTYPE html>
<html>

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function goTo() {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?key=api&format=json&q=" + link_id.value, function(result, status, jqXHR) {
var myList = (jqXHR.responseText);
var columns = addAllColumnHeaders(myList);

for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];

if (cellValue == null) {
cellValue = "";
}

row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
);}


function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');

for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#excelDataTable").append(headerTr$);

return columnSet;
}​
</script>
</head>

<body>

<h2> Search box </h2>
<input type='text' id='link_id'>
<input type='button' id='link' value='Search' onClick='goTo()'>
<table id="excelDataTable" border="1" />

<div></div>

</body>

</html>

我得到了以下结果:

enter image description here

在 chrome 中,我什至无法查看

最佳答案

我得到的响应是一个对象而不是数组。将响应作为对象处理。

function goTo() {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?key=api&format=json&q=" + link_id.value, function(result, status, jqXHR) {
var myList = (jqXHR.responseText);
myList = JSON.parse(myList);
console.log(myList);
var keys = [];
for (var key in myList) {
keys.push(key);
}
addAllColumnHeaders(myList, keys);
var row$ = $('<tr/>');

for (var i = 0; i < keys.length; i++) {

var key = keys[i];
var cellValue = myList[key];

if (cellValue == null) {
cellValue = "";
} else if (typeof cellValue == "object") {
cellValue = JSON.stringify(cellValue);
}

row$.append($('<td/>').html(cellValue));
}

$("#excelDataTable").append(row$);
});
}


function addAllColumnHeaders(myList, keys) {

var columnSet = [];
var headerTr$ = $('<tr/>');

for (var i = 0; i < keys.length; i++) {
var key = keys[i];
headerTr$.append($('<th/>').html(key));
}
$("#excelDataTable").append(headerTr$);

return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2> Search box </h2>
<input type='text' id='link_id'>
<input type='button' id='link' value='Search' onClick='goTo()'>
<table id="excelDataTable" border="1" />

<div></div>

关于javascript - 使用 jquery 为任何字段在 javascript 中从 json 创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31015100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com