未捕获类型错误:undefied 不是 JSON 响应的函数

uncaught type error :undefiened is not a function for JSON response

本文关键字:JSON 不是 响应 函数 undefied 类型 错误      更新时间:2023-09-26

嗨,我正在使用 json 将歌曲列表发送到我的表。在控制器 url 之前,json 响应正常。但是当我尝试遍历它并将详细信息放在我的表中时,我收到此错误。

  $(window).load(function(){
        $.get("/MusicPlayer/getSongList", function(data){
         var library = data;
         listSongs(library);
    });
}); 

 function listSongs(library){
 var table = $("#table");
 var row;
 $("#table tbody").remove();
 library.forEach(function(song){ ***/*this is the line where there is error. */*** 
     row = $("<tr></tr>");
        $("<td />").addClass("song-select").append($("<input  
        />").attr({type:"checkbox",class:"checkbox",value:song.title})).appendTo(row);
        $("<td>"+song.title+"</td>").appendTo(row);
        $("<td>"+song.album+"</td>").appendTo(row);
        $("<td>"+song.artist+"</td>").appendTo(row);
        $("<td>"+song.rating+"</td>").appendTo(row);
        $("<td>"+song.composer+"</td>").appendTo(row);
        $("<td>"+song.genre+"</td>").appendTo(row);
        row.click(viewFunction());
        row.appendTo(table);
 });

 [
{
    "title": "15 - Jacob's Theme.mp3",
    "album": "The Twilight Saga - Eclipse",
    "artist": "Howard Shore",
    "rating": "2",
    "composer": "carter ruwell",
    "genre": "Soundtrack"
},
{
    "title": "07_-_Vennante.mp3",
    "album": "Andala Rakshasi (2012)",
    "artist": "Ranjith",
    "rating": "0",
    "composer": "Rathan",
    "genre": "TeluguMusic"
},
{
    "title": "08. One Simple Idea.mp3",
    "album": "Inception (OST)",
    "artist": "Hans Zimmer",
    "rating": "0",
    "composer": "null",
    "genre": "?????????"
}
   ]

我想你需要$.parseJSON,因为library应该是一个 JSON 格式的字符串,而不是一个真正的数组。

$.parseJSON(library).forEach(function(song){ .....

json响应是一个非常特定格式的字符串,但仍然只是一个字符串。

在能够将其用作Javascript数据之前,您需要使用JSON.parse解析它。

JSON 对象没有为其定义forEach函数。

用于循环 :

for(var song in library) {
   console.log(song, result[song]);
}

或使用 jquery each

$.each(library, function(key, value) {
});​

forEach仅适用于简单数组和支持ECMAScript5 的环境中。也看看这个:在 JavaScript 中的数组上 for-each?