json-api和错误结果:无法读取属性'长度'的未定义

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

本文关键字:长度 未定义 属性 读取 错误 结果 json-api      更新时间:2023-09-26

我一直在找不到如何解决的问题。当我运行代码时,它会告诉我"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.

从我所看到的,您希望"actors"数组是"data"(即Result变量)的直接属性。但是,您提供的示例数据显示,在两者之间有一个"moveies"数组。因此,在内部,.each函数将试图计算Result.actors的长度…但Result.actor不存在,因此它被认为是未定义的。

你有一系列的电影,所以你需要先循环播放这些电影,然后循环播放其中的演员。

我在这里使用您提供的数据和我使用的处理代码创建了一个工作示例。缺少的只是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>