繁体   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