簡體   English   中英

json api 和錯誤結果:無法讀取未定義的屬性“長度”

[英]json api and result with error: Cannot read property 'length' of undefined

我不斷得到一些我不知道如何解決的東西。 當我運行代碼時,它告訴我“未捕獲的類型錯誤:無法讀取未定義的屬性‘長度’ ”。 通過大量搜索和閱讀,我沒有找到答案,它提到我需要將值的長度與 for 命令一起使用,但是我嘗試了幾種解決方案,但沒有一個解決了問題,這是代碼:

function Cast() {
$.ajax({
    type: "Get",
    url: "http://www.myapifilms.com/imdb/idIMDB?idIMDB=tt2193418&token=<TOKEN>&format=json&callback=?&actors=2",
    dataType: "json",
    success: function (Result)    
    {
        $.each(Result.actors, function (i, item)  {
        $('.div').append('<tr><td>' + Result.actors[i].actorName + '</td></tr>');              

        });
    },
    error: function () {
        console.log("Error, Something went wrong!");
    }
});

}

我從郵遞員那里得到的答復:

{
"data": {
"movies": [
  {
    "title": "Hammer of the Gods",
    "simplePlot": "A young man transforms into a brutal warrior as he travels the unforgiving landscape in search of his long lost brother, Hakan the Ferrocious, whose people are relying on him to restore order to their kingdom.",
    "actors": [
      {
        "actorName": "Charlie Bewley",
      },
      {
        "actorName": "Clive Standen",
      etc.

從我所見,您希望“演員”數組是“數據”的直接屬性(即您的 Result 變量)。 但是您提供的示例數據表明兩者之間有一個“movies”數組。 因此錯誤 - 在內部 .each 函數將嘗試計算 Result.actors 的長度......但 Result.actors 不存在,因此它說它是未定義的。

您有一系列電影,因此您需要先循環播放這些電影,然后循環播放其中的演員。

我在這里使用您提供的數據和我使用的處理代碼創建了一個工作示例。 缺少的只是 Ajax 位,我只是將數據直接放入一個變量中,但這無關緊要。

 $(function() { var Result = { "data": { "movies": [ { "title": "Hammer of the Gods", "simplePlot": "A young man transforms into a brutal warrior as he travels the unforgiving landscape in search of his long lost brother, Hakan the Ferrocious, whose people are relying on him to restore order to their kingdom.", "actors": [ { "actorName": "Charlie Bewley", }, { "actorName": "Clive Standen", } ] } ] } }; $.each(Result.data.movies, function (i, movie) { $.each(movie.actors, function (j, actor) { $('.div').append('<tr><td>' + actor.actorName + '</td></tr>'); }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="div"> </table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM