使用ajax和amp;显示来自多个json对象的数组jQuery的

时间:2017-07-26 04:12:48

标签: jquery json ajax

我有多个类似于下面的对象。我想显示mealReviews:[]数组从所有多个json对象变成$('#mealDetails')。html()。

 {
"_id": {
    "$oid": "59ef162f7afc7636"
},
"mealIDa": "ACT",
"mealIDb": "TMNT2",
"title": "Teenage Mutant Ninja Turtles 2 The Secret of the Ooze",
"description": "The Teenage Mutant Ninja Turtles (Mark Caso, Michelan Sisti, Leif Tilden, Kenn Troum) again battle their archenemy, the rogue ninja Shredder (Francois Chau). Shredder attempts revenge by obtaining the same radioactive ooze that created the Turtles and unleashing two new monstrous mutants: Tokka, an oversized snapping turtle, and Rahzar, a fearsome wolf-like creature. When Shredder plans to use the remaining ooze on himself, the Turtles must harness their ninja fighting skills to stop him.",
"releaseDate": "March 22, 1991",
"language": "English",
"subtitle": false,
"srt": "Teenage Mutant Ninja Turtles II The Secret of the Ooze.srt",
"director": "Michael Pressman",
"actors": "Paige Turco \"April O'Neil\", Vanilla Ice, Michelan Sisti \"Michelangelo, Soho Man\", Robbie Rist \"Michelangelo\", Kevin Clash \"Splinter\"",
"studio": "Golden Harvest Company, New Line Cinema, Northshore Investments Ltd.",
"hrs": 1,
"mins": 28,
"ratings": "PG \u2013 Parents Cautioned",
"dateAdded": "2017-07-18T20:59:17.473Z",
"mealReviews": [
    {
        "username": "dwaynekshrn",
        "accountType": "cop",
        "subject": "Lucky Award Winners",
        "rating": "1",
        "review": "I really think this movies deserves an academy award",
        "reviewDate": "2017-07-25T23:29:53.371Z"
    },
    {
        "username": "dwaynekshrn",
        "accountType": "cop",
        "subject": "One on the shot clock",
        "rating": "1",
        "review": "He shoots, he scores!",
        "reviewDate": "2017-07-24T22:58:17.622Z"
    },
    {
        "username": "shaolinkyle",
        "accountType": "monk",
        "subject": "In da house",
        "rating": "1",
        "review": "Shaolin Kyle is in the house!",
        "reviewDate": "2017-07-24T22:47:56.056Z"
    },
    {
        "username": "dwaynekshrn",
        "accountType": "cop",
        "subject": "Political Spectrum",
        "rating": "1",
        "review": "is dope son!",
        "reviewDate": "2017-07-24T22:51:51.106Z"
    }
   ]
}

我正在从ajax请求中检索数据,但是当我用console.log检查数据时,它似乎没有返回数据。它在我定位特定对象时有效但当我尝试从所有对象获取相同数据时,我正在绘制一个空白。

$.ajax({
  url: url,
  type: 'GET',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data){
  $('#mealDetails').empty();
  // test to see if retrieving data
  console.log(data.title);
  var reviews = [];
  var output = '<div>';
  $.each(data.mealReviews, function(key, value) {
    output += '<div class="row">';
    output += '<div class="col-sm-3 col-sm-offset-1 col-md-3 col-md-
    offset-1"><img class="img-thumbnail" src="images/' + 
     this.accountType +'.png" width="200" height="200" alt="">';
    output += '<p>By <a>'+ this.username +'</a> '+ this.reviewDate +'</p></div>';
    output += '<div class="col-sm-8 col-md-8"><div class="row">';
    output += '<h2>'+ this.rating +'<span class="glyphicon glyphicon-star"></span> '+ this.subject +'</h2>';
    output += '<p class="textFormat">'+ this.review +'</p></div></div>';
    output += '</div>';
  });

output += '</div>';
reviews.push(output);
$('#mealDetails').html(output);


},
error:function(xhr,status,err){
  console.log('nah bruh thats a no go');
}

  });

4 个答案:

答案 0 :(得分:0)

替换

this.accountTypevalue.accountType

表示您必须将所有this.替换为value.

内的$.each(....)

答案 1 :(得分:0)

在这里,您将使用示例解决方案https://jsfiddle.net/j4r3dcxr/

var data1 ={
	"_id": {
		"$oid": "59ef162f7afc7636"
	},
	"mealIDa": "ACT",
	"mealIDb": "TMNT2",
	"title": "Teenage Mutant Ninja Turtles 2 The Secret of the Ooze",
	"description": "The Teenage Mutant Ninja Turtles (Mark Caso, Michelan Sisti, Leif Tilden, Kenn Troum) again battle their archenemy, the rogue ninja Shredder (Francois Chau). Shredder attempts revenge by obtaining the same radioactive ooze that created the Turtles and unleashing two new monstrous mutants: Tokka, an oversized snapping turtle, and Rahzar, a fearsome wolf-like creature. When Shredder plans to use the remaining ooze on himself, the Turtles must harness their ninja fighting skills to stop him.",
	"releaseDate": "March 22, 1991",
	"language": "English",
	"subtitle": false,
	"srt": "Teenage Mutant Ninja Turtles II The Secret of the Ooze.srt",
	"director": "Michael Pressman",
	"actors": "Paige Turco \"April O'Neil\", Vanilla Ice, Michelan Sisti \"Michelangelo, Soho Man\", Robbie Rist \"Michelangelo\", Kevin Clash \"Splinter\"",
	"studio": "Golden Harvest Company, New Line Cinema, Northshore Investments Ltd.",
	"hrs": 1,
	"mins": 28,
	"ratings": "PG \u2013 Parents Cautioned",
	"dateAdded": "2017-07-18T20:59:17.473Z",
	"mealReviews": [{
			"username": "dwaynekshrn",
			"accountType": "cop",
			"subject": "Lucky Award Winners",
			"rating": "1",
			"review": "I really think this movies deserves an academy award",
			"reviewDate": "2017-07-25T23:29:53.371Z"
		},
		{
			"username": "dwaynekshrn",
			"accountType": "cop",
			"subject": "One on the shot clock",
			"rating": "1",
			"review": "He shoots, he scores!",
			"reviewDate": "2017-07-24T22:58:17.622Z"
		},
		{
			"username": "shaolinkyle",
			"accountType": "monk",
			"subject": "In da house",
			"rating": "1",
			"review": "Shaolin Kyle is in the house!",
			"reviewDate": "2017-07-24T22:47:56.056Z"
		},
		{
			"username": "dwaynekshrn",
			"accountType": "cop",
			"subject": "Political Spectrum",
			"rating": "1",
			"review": "is dope son!",
			"reviewDate": "2017-07-24T22:51:51.106Z"
		}
	]
};

var data2 ={
	"_id": {
		"$oid": "59ef162f7afc7636"
	},
	"mealIDa": "ACT",
	"mealIDb": "TMNT2",
	"title": "Teenage Mutant Ninja Turtles 2 The Secret of the Ooze",
	"description": "The Teenage Mutant Ninja Turtles (Mark Caso, Michelan Sisti, Leif Tilden, Kenn Troum) again battle their archenemy, the rogue ninja Shredder (Francois Chau). Shredder attempts revenge by obtaining the same radioactive ooze that created the Turtles and unleashing two new monstrous mutants: Tokka, an oversized snapping turtle, and Rahzar, a fearsome wolf-like creature. When Shredder plans to use the remaining ooze on himself, the Turtles must harness their ninja fighting skills to stop him.",
	"releaseDate": "March 22, 1991",
	"language": "English",
	"subtitle": false,
	"srt": "Teenage Mutant Ninja Turtles II The Secret of the Ooze.srt",
	"director": "Michael Pressman",
	"actors": "Paige Turco \"April O'Neil\", Vanilla Ice, Michelan Sisti \"Michelangelo, Soho Man\", Robbie Rist \"Michelangelo\", Kevin Clash \"Splinter\"",
	"studio": "Golden Harvest Company, New Line Cinema, Northshore Investments Ltd.",
	"hrs": 1,
	"mins": 28,
	"ratings": "PG \u2013 Parents Cautioned",
	"dateAdded": "2017-07-18T20:59:17.473Z",
	"mealReviews": [{
			"username": "dwaynekshrn",
			"accountType": "cop",
			"subject": "Lucky Award Winners",
			"rating": "1",
			"review": "I really think this movies deserves an academy award",
			"reviewDate": "2017-07-25T23:29:53.371Z"
		},
		{
			"username": "dwaynekshrn",
			"accountType": "cop",
			"subject": "One on the shot clock",
			"rating": "1",
			"review": "He shoots, he scores!",
			"reviewDate": "2017-07-24T22:58:17.622Z"
		},
		{
			"username": "shaolinkyle",
			"accountType": "monk",
			"subject": "In da house",
			"rating": "1",
			"review": "Shaolin Kyle is in the house!",
			"reviewDate": "2017-07-24T22:47:56.056Z"
		},
		{
			"username": "dwaynekshrn",
			"accountType": "cop",
			"subject": "Political Spectrum",
			"rating": "1",
			"review": "is dope son!",
			"reviewDate": "2017-07-24T22:51:51.106Z"
		}
	]
};

getData = function(data){
	var reviews = [];
  var output = '<div>';
  $.each(data.mealReviews, function(key, value) {
    output += '<div class="row">';
    output += '<div class="col-sm-3 col-sm-offset-1 col-md-3 col-md-offset-1"><img class="img-thumbnail" src="images/' + 
     data.mealReviews[key].accountType +'.png" width="200" height="200" alt="">';
    output += '<p>By <a>'+ this.username +'</a> '+ data.mealReviews[key].reviewDate +'</p></div>';
    output += '<div class="col-sm-8 col-md-8"><div class="row">';
    output += '<h2>'+ this.rating +'<span class="glyphicon glyphicon-star"></span> '+ data.mealReviews[key].subject +'</h2>';
    output += '<p class="textFormat">'+ data.mealReviews[key].review +'</p></div></div>';
    output += '</div>';
  });

  output += '</div>';
  reviews.push(output);
  $('body').append(output);
}

getData(data1);
getData(data2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我不确定你是否在寻找这个...... 我没有使用AJAX调用,而是将数据保存在两个不同的变量中,并将这些数据传递给一个函数(无论你在AJAX成功方法中拥有它)。

我没有将.html用于正文或特定容器(id / class),而是使用.append()来附加数据。

答案 2 :(得分:0)

每个都使用匿名方法循环,​​因此this在上下文中丢失了您实际想要的内容。您应该使用$ .each循环中的值param来引用正在迭代的项目。

var reviews = [];
var output = '<div>';
$.each( data.mealReviews, function( key, value ) {
output += '<div class="row">';
output += '<div class="col-sm-3 col-sm-offset-1 col-md-3 col-md-offset-1"><img class="img-thumbnail" src="images/' + 
 value.accountType +'.png" width="200" height="200" alt="">';
output += '<p>By <a>'+ value.username +'</a> '+ value.reviewDate +'</p></div>';
output += '<div class="col-sm-8 col-md-8"><div class="row">';
output += '<h2>'+ value.rating +'<span class="glyphicon glyphicon-star"></span> '+ value.subject +'</h2>';
output += '<p class="textFormat">'+ value.review +'</p></div></div>';
output += '</div>';
});

output += '</div>';
reviews.push(output);
$( '#mealDetails' ).html( output );

小提琴:https://jsfiddle.net/8bc3hdqp/

修改: 如果你的意思是你的返回实际上有一个多个对象的数组,就像你显示的那样,那么你将循环遍历这些对象,然后循环遍历内容:

var reviews = [];
var output = '<div>';
$.each( data, function( k, v ) {
    $.each( data[k].mealReviews, function( key, value ) {
        output += '<div class="row">';
        output += '<div class="col-sm-3 col-sm-offset-1 col-md-3 col-md-offset-1"><img class="img-thumbnail" src="images/' + value.accountType +'.png" width="200" height="200" alt="">';
        output += '<p>By <a>'+ value.username +'</a> '+ value.reviewDate +'</p></div>';
        output += '<div class="col-sm-8 col-md-8"><div class="row">';
        output += '<h2>'+ value.rating +'<span class="glyphicon glyphicon-star"></span> '+ value.subject +'</h2>';
        output += '<p class="textFormat">'+ value.review +'</p></div></div>';
        output += '</div>';
    });
});

output += '</div>';
reviews.push(output);
$( '#mealDetails' ).html( output );

小提琴:https://jsfiddle.net/8bc3hdqp/1/

您可以尝试使用console.log(JSON.stringify(data))将对象转换为字符串来控制对象的日志记录。如果这有助于为你调试事情(不确定你的意思是你没有在响应中看到任何内容)。

答案 3 :(得分:0)

我找到了问题的解决方案。起初我的问题是所有对象在mealReviews Array中没有相同的数据。有些人有一个带有对象的数组,而有些人有一个字符串会导致我的应用程序崩溃。所以我做了一个if语句只用一个数组过滤了mealReviews。然后我创建了另一个只显示没有空对象的数组的if语句。

 $.get(url).done(function(data){
 var reviews = [];
 var output = '<div>';
 $.each( data, function( k, v ) {
 if (data[k].mealReviews instanceof Array){
 $.each( data[k].mealReviews, function( key, value ) {
   if(value.username){
  output += '<div class="thumbnail row">';
  output += '<div class="col-sm-3 col-sm-offset-1 col-md-3 col-md-offset-1"><img class="img-thumbnail" src="images/' + value.accountType +'.png" width="200" height="200" alt="">';
  output += '<p>By <a>'+ value.username +'</a> '+ value.reviewDate +'</p></div>';
  output += '<div class="col-sm-8 col-md-8"><div class="row">';
  output += '<h2>'+ value.rating +'<span class="glyphicon glyphicon-star"></span> '+ value.subject +'</h2>';
  output += '<p class="textFormat">'+ value.review +'</p></div></div>';
  output += '</div>';
  }
 });
}

});

 output += '</div>';
 reviews.push(output);
 $( '#mealDetails' ).prepend(output);
});