2015-10-15 144 views
1

我正在使用简单的JSON Ajax请求来获取一些JSON数据。 但是,所有的时间,我尝试使用JSON对象,我得到了以下问题:简单请求:未捕获TypeError:无法读取未定义的属性“长度”

Uncaught TypeError: Cannot read property 'length' of undefined

$(document).on('pageinit', '#home', function() { 
    $.ajax({ 
     url: "http://localhost/documents.json", 
     dataType: "json", 
     type: 'GET', 
     async: true, 
     success: function(result) { 
      //ajax.parseJSON(result); 
      $.each(result, function(idx, obj) { 
       alert(obj.name); 
      }); 
     }, 
     error: function(request, error) { 
      alert('Network error has occurred please try again!' + ' ' + request + ' ' + error); 
     } 
    }); 
}); 

我的JSON文件是有效的,看起来像这样:

{ 
    "books": [{ 
    "id": "01", 
    "name": "info", 
    "dateiname": "info.pdf" 
    }, { 
    "id": "02", 
    "name": "agb", 
    "dateiname": "agb.pdf" 
    }, { 
    "id": "03", 
    "name": "raumplan", 
    "dateiname": "raumplan.pdf" 
    }, { 
    "id": "04", 
    "name": "sonstiges", 
    "dateiname": "sonstiges.pdf" 
    }, { 
    "id": "05", 
    "name": "werbung", 
    "dateiname": "werbung.pdf" 
    }] 
} 
+0

这是你的console.log成功的结果吗? – guradio

+0

如何/你在哪里检查什么是“长度”? – Tushar

+0

@Pekka是的,这是控制台输出。我没有检查任何东西。我只想解析JSON文件并将其添加到列表视图 – jublikon

回答

0

您应该执行类似如下:

if(result && result["books"]) { 
    $.each(result["books"], function(idx, obj) { 
     alert(obj.name); 
    }); 
} 
+0

'jQuery.each'可以在一个对象上循环。 – Magus

+0

@Magus是的,'jQuery.each'可以在一个对象上循环,但'result'不是一个数组。 – Flea777

0

jQuery.each如果您提供0123价值。但是result不能被定义,否则jQuery会抛出JSON解析错误。至少result是一个空对象{}(或一个空数组[])。

你的代码从来没有读过任何东西的length。所以我假设你的错误是在你的代码中的其他地方。

仔细检查控制台中的错误。你应该有错误的确切路线。还有堆栈。

但是你的代码仍然存在错误。你应该有这个:

$.each(result.books, function(idx, obj) { 
    alert(obj.name); 
}); 
相关问题