首页 > 解决方案 > $.each 没有遍历所有来自 ajax 响应的对象

问题描述

我从console.log(). 但是,网站中只有一个数据显示为输出。

我尝试使用$.each来自 AJAX 的响应,但它只显示来自一个对象的数据。我希望所有三个对象的数据都显示在网站中。

$.ajax({
  url: '/process/archiveFull1.php',
  type: 'POST',
  data: {
    id: 2018,
  },
  success: function(response) {
    if (typeof(response) != 'object') {
      response = $.parseJSON(response);
    }

    if (response.status.status == true) {
      $.each(response.body, function(key, value) {
        html_option = "<div class='carousel-inner'><div class='carousel-item active'><div class='top-with-controls-archive text-center'>" + value.id + "</h4></div><div class='body-archive'><div class='row py-2'><div class='col-md-3 col-sm-6'><a href='" + value.added_date + "'><img src='" + value.image + "' class='img-fluid'></a></div></div></div>";
      });
      $('#wrap').html(html_option);
    }
  }
});

编辑:这是我收到的回复这里

标签: jqueryajaxloopseach

解决方案


html每次循环都会覆盖变量,所以最后它只包含最后一个对象的输出。您需要连接而不是替换。

    if (response.status.status == true) {
      var html_option = '';
      $.each(response.body, function(key, value) {
        html_option += "<div class='carousel-inner'><div class='carousel-item active'><div class='top-with-controls-archive text-center'>" + value.id + "</h4></div><div class='body-archive'><div class='row py-2'><div class='col-md-3 col-sm-6'><a href='" + value.added_date + "'><img src='" + value.image + "' class='img-fluid'></a></div></div></div>";
      });
      $('#wrap').html(html_option);
    }

推荐阅读