json api并出现错误:无法读取未定义的属性'length'

问题描述 投票:1回答:1

我不断得到一些我找不到解决方法的东西。当我运行代码时,它告诉我“ Uncaught TypeError:无法读取未定义的属性'length'”。经过大量的搜索和阅读,我没有找到答案,但它提到我需要使用带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.
javascript jquery json ajax api
1个回答
2
投票

据我所见,您期望“ actors”数组是“ data”的直接属性(即您的Result变量)。但是随后您提供的示例数据显示,两者之间存在一个“运动”阵列。因此,错误-内部的.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>
© www.soinside.com 2019 - 2024. All rights reserved.