[英]How can I print my JSON data?
I try to get a JSON file on my local host but on console I receive an array with my all objects from data.json but I receive the following error 我尝试在本地主机上获取JSON文件,但是在控制台上,我从data.json接收到包含所有对象的数组,但是出现以下错误
Uncaught TypeError: Cannot read property 'forEach' of undefined
This is my code: 这是我的代码:
$.ajax({
type : 'GET',
dataType : 'json',
url: 'http://localhost:8888/data/folder/data.json',
success : function(data) {
console.log(data);
var data =[];
var covers = document.getElementById("covers");
var blockTemplate = covers.getElementsByTagName("div")[0].cloneNode(true);
covers.getElementsByTagName("div")[0].remove();
data.info.forEach( function(obj) {
block = blockTemplate.cloneNode(true);
block.getElementsByTagName("a")[0].setAttribute('href', obj.link);
block.getElementsByTagName("img")[0].setAttribute('src', obj.cover);
covers.appendChild(block);
});
}
});
Any idea how can I solve this? 知道我该如何解决吗?
Remove 去掉
var data =[];
From success()
. 从
success()
。
This is overriding the ajax
response. 这覆盖了
ajax
响应。
var data = data.info; data.forEach( function(obj) { block = blockTemplate.cloneNode(true); block.getElementsByTagName("a")[0].setAttribute('href', obj.link); block.getElementsByTagName("img")[0].setAttribute('src', obj.cover); covers.appendChild(block); });
Change success : function(data) {
with success : function(response) {
response in success
and your data array
is ambiguous. 更改
success : function(data) {
与success : function(response) {
success
响应,并且您的data array
不明确。 This will create problem. 这会造成问题。 In javascript variables overrides when you'll define again.
在javascript中,变量将在您再次定义时覆盖。
Take a look here 在这里看看
What is the scope of variables in JavaScript? JavaScript中变量的范围是什么?
In your case I think that "info" object of "data" is not defined or not received from server. 在您的情况下,我认为未定义或未从服务器接收到“数据”的“信息”对象。
You can also loop your json object as shown below : 您还可以如下所示循环json对象:
if(typeof(data.info) != "undefined")
for(i in data.info)
{
var obj = data.info[i];
block = blockTemplate.cloneNode(true);
block.getElementsByTagName("a")[0].setAttribute('href', obj.link);
block.getElementsByTagName("img")[0].setAttribute('src', obj.cover);
covers.appendChild(block);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.