我试图从 openwheater 应用程序打印表中的一些 JSON 数据。 我在互联网上搜索了解决方案,但找不到真正的解决方案。 我是初学者,所以这可能是一个非常简单的错误
希望有人能帮助我走上正确的道路
错误:
Cannot read property 'createDocumentFragment' of undefined
这是我的简短代码
$( document ).ready(function() {
function fillTable(oJSON) {
$("#theTable").html("");
for( var w in oJSON ) {
var row = $('<tr></tr>').appendTo($("#theTable")).data(oJSON[w]);
$('<td></td>').text(oJSON[w].temp).appendTo(row);
$('<td></td>').text(oJSON[w].description).appendTo(row);
}
}
jQuery.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q={Zwolle}",
type: "GET",
success: function(oJSON) {
fillTable(oJSON);
},
error : function(jqXHR, textStatus, errorThrown) {
},
timeout: 120000,
});
});
返回的 JSON 为:
{
"coord": {
"lon": 6.09,
"lat": 52.51
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"base": "cmc stations",
"main": {
"temp": 292.93,
"pressure": 1002,
"humidity": 68,
"temp_min": 290.93,
"temp_max": 293.75
},
"wind": {
"speed": 6.7,
"deg": 172.504
},
"rain": {
"3h": 1.3
},
"clouds": {
"all": 80
},
"dt": 1440446526,
"sys": {
"type": 3,
"id": 140484,
"message": 0.0083,
"country": "NL",
"sunrise": 1440390831,
"sunset": 1440441644
},
"id": 2743476,
"name": "Gemeente Zwolle",
"cod": 200
}
最佳答案
当你使用 jQuery 的 data()
时,你必须更加小心。
当您将 data
与单个字符串一起使用时,如 data("cmc station")
中,它会尝试获取该值并返回结果。
当您传递 data
一个对象时,它会在 jQuery 的内部数据对象中设置键和值,然后返回您想要的元素。
您正在迭代该对象,并执行操作
var row = $('<tr></tr>').appendTo($("#theTable")).data(oJSON[w]);
您期望 row
成为一个元素,但在该循环中您最终得到
var row = $('<tr></tr>').appendTo($("#theTable")).data("cmc stations");
并且row
突然未定义
,因为没有可返回的键“cmc station”
的数据,并且由于jQuery内部可以如果未在 undefined
上调用 createDocumentFragment
,则会出现该错误。
解决方案是将内容写在单独的行上,或者更仔细地检查您传递给 data
的内容以及 row
的实际内容。
看来你想要的是
function fillTable(oJSON) {
$("#theTable").append(
$('<tr />').append(
$('<td />').text(oJSON.main.temp),
$('<td />').text(oJSON.main.description)
)
);
}
$(document).ready(function () {
jQuery.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q={Zwolle}",
type: "GET",
success: function (oJSON) {
fillTable(oJSON);
},
error: function (jqXHR, textStatus, errorThrown) {},
timeout: 120000,
});
});
关于javascript - 无法读取未定义的属性 'createDocumentFragment',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32190840/