$.each 不遍历 ajax 响应中的所有对象

$.each not looping through all the object coming in ajax response

我从 console.log() 中的 AJAX 响应中获得了 3 个对象。但是,只有一个数据在网站上显示为输出。

我试过使用 $.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);
    }
  }
});

编辑: 这是我收到的回复

您每次循环都会覆盖 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);
    }

鉴于您的控制台快照中显示的响应内容,它是一个对象数组。因此,您需要遍历它们,并在该循环的每次迭代中附加新的 HTML 。目前你每次都是 over-writing 以前的值。试试这个:

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

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

请注意,您显示的响应中似乎没有任何 bodystatus 属性,因此请确保响应如您预期的那样返回。

错误在这行代码中。

 html_option = "<div class='carousel-inner'>..........................

您正在做的是在第一次迭代期间将值存储在 html_option 中,然后用第二次迭代的值替换它,然后用第三次迭代的值替换它。所以最后你的 html_option 只包含一组值。

您应该将上面的代码替换为

html_option += "<div class='carousel-inner'>..........................

“+=”将每组值添加到 html_option,而不替换前一组值。

或者您可以使用追加。 http://api.jquery.com/append/