Как перезагрузить функцию вызова AJAX в данный момент - программирование

Как перезагрузить функцию вызова AJAX в данный момент

У меня была задача, которую я почти выполнил, но я застрял в последней части.

Что я делаю

  • У меня есть данные JSON из серверной части, которые я вызываю сразу, затем показываю их как таблицу HTML, но только 10 строк за раз. Если строк больше 10, то они будут отображаться в двух частях: сначала 10, затем через 5 секунд, следующие 10, Вы можете проверить мой фрагмент для этого
  • Когда это будет последняя страница таблицы, то, что я делаю, показывает изображение, если изображение одно, то table--> изображение, если имеется более одного изображения, предположим, что там 2 изображения, чем table--> image1 → table--> image2 вот так работает
  • Когда цикл завершается как table--> image, я снова вызываю табличную функцию, потому что она будет иметь динамические данные
  • Здесь данные изображения также поступают в формате JSON, и они также динамичны, там я сталкиваюсь с проблемой

вопрос

  • У меня есть функция imageFormatter() которая имеет данные для изображения в формате JSON
  • Эти изображения установлены в моей базе данных как имя столбца IsActive поэтому при вызове этих данных я проверяю это условие в моей базе данных с помощью запроса
  • Теперь моя таблица отображается на интерфейсе пользователя, и iamges тоже, но в моей базе данных этот флаг IsActive может быть изменен в любое время с Y на N
  • Теперь я пытаюсь сделать так, чтобы функция imageFormatter() обновлялась каждые 5 секунд, чтобы она могла принимать новые данные.
  • Чтобы изменить это IsActive меня есть пользовательский интерфейс, который пользователь щелкает по ходу, независимо от того, какое изображение выберет пользователь. Я imageFormatter() его в БД через servlet, теперь просто хочу показать вызов этого imageFormatter() чтобы он мог принимать новейшие изображения.

Это подход, который я использую для выполнения своей задачи. Есть ли лучший подход?

Я прокомментировал все строки в моем коде для лучшего понимания

function myFun() {
  imageFormatter(); // here  I am calling because it will call again and again
  $.ajax({

    url: "MenuCounter",
    method: "GET",
    data: {
      counterCode: counterCode
    },
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(tableValue) {

      // tableValue i have provided in my code/post

      if (tableValue[0].outlet === 'NoData') {
        $.alert({
          title: 'Alert!',
          content: 'Display content Not available',
          onDestroy: function() {

          }
        });
      } else {

        addTable(tableValue, color1, color2, color3, color4) // colors are some colors
        showRows();

        interval = window.setInterval(showRows, 5000);



      }

    }
  });
}

$.ajax({
  async: true,
  url: "MenuCounterName",
  method: "GET",
  dataType: "json",
  data: {
    counterCode: counterCode
  },
  contentType: "application/json; charset=utf-8",
  success: function(data) { // geting counter name to display on to such as 'Dosa Corner'
    if (data[0].outlet === 'NoData') {
      $.alert({
        title: 'Alert!',
        content: 'Display content Not available',
        onDestroy: function() {

        }
      });
    } else {
      // console.log(data[0]["Counter name"])
      $("#counterName").text(data[0]["Counter name"])
      color1 = data[0].Color1;
      color2 = data[0].Color2;
      color3 = data[0].Color3;
      color4 = data[0].Color4;

      myFun(); // this function is calling data from db

      $(".loader").hide();
      $(".overlay").hide();

    }
  }
});

function hideImage() {
  var imgno = (cnt % imgLen) + 1;
  $("#displayImage img").css("display", "none");
  $("#displayImage img:nth-child(" + imgno + ")").css("display", "block")

  $("#displayImage").show(); // show Image and hide table
  $("#DisplayTable").hide();

  setTimeout(function() {
    myFun();
    // I am calling my function after the last image is shown because it will call from db

  }, 5000);
  cnt++;
}


function showRows() {

  if ($(".hidden:lt(11)").length > 0) {
    $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
    $("#displayImage").hide();
    $("#DisplayTable").show();
  } else {
    $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
    hideImage();

    clearInterval(interval);

  }

  $(".hidden:lt(11)").removeClass("hidden");
}

function addTable(tableValue, color1, color2, color3, color4) {

  var $tbl = $("<table />", {
      "class": "table fixed"
    }),
    $tb = $("<tbody/>");
  $trh = $("<tr/>");

  var split = Math.round(tableValue.length / 4);
  for (i = 0; i < split; i++) {
    $tr = $("<tr/>", {
      class: "hidden w3-animate-zoom"
    });
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {
        if (typeof(value) === "number") {
          $("<td/>", {
            "class": "text-right color" + (j + 1)
          }).html(value).appendTo($tr);
        } else {
          $("<td/>", {
            "class": "text-left color" + (j + 1)
          }).html(value).appendTo($tr);
        }
      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);
  var winHeight = ($(window).height() - 10);
  var HeadingHeight = $("#counterName").height();
  var heightForCells = (winHeight - HeadingHeight) / 11;
  $(".color1").css({
    "background": color1,
    "height": heightForCells
  });
  $(".color2").css({
    "background": color2
  });
  $(".color3").css({
    "background": color3
  });
  $(".color4").css({
    "background": color4
  });

}




/* setInterval(function(){
	 imageFormatter();// this will run after every 5 seconds
 }, 5000);
	*/


function imageFormatter() {  // this is my image function trying to call it with myfun() because myFun is dynamically calling after the last Image so it will also get called
  // clearInterval(interval);
  $.ajax({
    'url': 'DisplayImage',
    'method': 'GET',
    data: {
      counterCode: counterCode
    },
    'success': function(images) {
      console.log(images)
      for (var key in images) {

        var imageList = images[key];
        for (i = 0; i < imageList.length; i++) {
          var img = $('<img />').attr({
            'src': 'Image/' + key + '/' + imageList[i],
            'alt': key + '/' + imageList[i],
            'class': 'hidden w3-animate-zoom',
            'width': 90 + "%",
            'height': 680
          }).appendTo('#displayImage');
        }

      }
      imgLen = $("#displayImage img").length;
    },

    'error': function(err) {

    }

  });


}
tbody>tr>td {
  white-space: normal;
  border-collapse: collapse;
  font-family: Verdana;
  font-weight: bold;
  font-size: .9em;
}

td:nth-child(2),
td:nth-child(4),
td:nth-child(6),
td:nth-child(8) {
  width: 85px;
  max-width: 85px;
  height: 63px
}

.fixed {
  table-layout: fixed;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden,
.already-shown {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="#" onclick="location.href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'; return false;">
<div id="DisplayTable"></div>
<div id="displayImage" style="display:none">

</div>
4b9b3361

Ответ 1

Попробуй это. Я добавил логику для перезагрузки, когда это последнее изображение.

$(document).ready(function() {

      var imgLen = 0;
      var cnt = 0;
      var lastImage = false;

      var tableValue = [{
      "Item Name": "MANCHOW  V SOUP",
      "SellingPrice": 100
    }, {
      "Item Name": "SMIRNOFF GREEN APPLE 60",
      "SellingPrice": 202
    }, {
      "Item Name": "SMIRNOFF GREEN APPLE30",
      "SellingPrice": 101
    }, {
      "Item Name": "BOMBAY SAPHIRE 750",
      "SellingPrice": 472
    }, {
      "Item Name": "BOMBAY SAPHIRE 30",
      "SellingPrice": 191
    }, {
      "Item Name": "BLUE RIBBAND 750",
      "SellingPrice": 877
    }, {
      "Item Name": "BLUE RIBBAND 60",
      "SellingPrice": 78
    }, {
      "Item Name": "BACCARDI WHITE 750",
      "SellingPrice": 248
    }, {
      "Item Name": "BACCARDI WHITE 180",
      "SellingPrice": 585
    }, {
      "Item Name": "BACCARDI WHITE 60",
      "SellingPrice": 202
    }, {
      "Item Name": "OLD MONK 180",
      "SellingPrice": 225
    }, {
      "Item Name": "OLD MONK 90",
      "SellingPrice": 168
    }, {
      "Item Name": "OLD MONK 60",
      "SellingPrice": 90
    }, {
      "Item Name": "OLD MONK 30 ",
      "SellingPrice": 45
    }, {
      "Item Name": "DON ANGEL 750",
      "SellingPrice": 466
    }, {
      "Item Name": "DON ANGEL 30",
      "SellingPrice": 191
    }, {
      "Item Name": "SAUZA SILVER 700",
      "SellingPrice": 615
    }, {
      "Item Name": "SAUZA SILVER 30",
      "SellingPrice": 270
    }, {
      "Item Name": "LIME WATER",
      "SellingPrice": 45
    }, {
      "Item Name": "PACKEGED WATER 1L",
      "SellingPrice": 39
    }, {
      "Item Name": "MANSION HOUSE 650",
      "SellingPrice": 900
    }, {
      "Item Name": "Chole Kulche",
      "SellingPrice": 80
    }, {
      "Item Name": "Butter Nan",
      "SellingPrice": 65
    }, {
      "Item Name": "Dhai",
      "SellingPrice": 20
    }, {
      "Item Name": "Rice",
      "SellingPrice": 55
    }, {
      "Item Name": "Plain rice",
      "SellingPrice": 30
    }, {
      "Item Name": "MANSION HOUSE 650",
      "SellingPrice": 900
    }, {
      "Item Name": "Chole Kulche",
      "SellingPrice": 80
    }, {
      "Item Name": "Butter Nan",
      "SellingPrice": 65
    }, {
      "Item Name": "Dhai",
      "SellingPrice": 20
    }, {
      "Item Name": "Rice",
      "SellingPrice": 55
    }, {
      "Item Name": "Plain rice",
      "SellingPrice": 30
    }];


      interval = '';
      var images = {
        CounterA: ["CounterA1.jpg", "CounterA2.jpg"]
      }
      initTable(tableValue);
      imageFormatter();

      function initTable(tableValue) {
        addTable(tableValue)
        showRows();
        interval = window.setInterval(showRows, 1000); // seting interval to show table in parts
      }




      function hideImage() {
        if(imgLen){
          var imgno = (cnt % imgLen) + 1; // here counting Image when it is last image want to refresh the oage using location.reload();
          console.log(imgLen, imgno);
          if(imgno == imgLen){
            console.log("reload now")
            location.reload();
          }
        //  console.log(imgno)
          $("#displayImage img").css("display", "none");
          $("#displayImage img:nth-child(" + imgno + ")").css("display", "block")

          $("#displayImage").show(); //show Image and hide table
          $("#DisplayTable").hide();
          setTimeout(function() {
            initTable(tableValue);
          }, 5000);
          cnt++;
         } else{
          initTable(tableValue);
         }

      }





      function showRows() {
        // Any TRs that are not hidden and not already shown get "already-shown" applies
        if ($(".hidden:lt(10)").length > 0) { //checking is it is the last page or not
          $("#displayImage").hide(); //showing table hiding image
          $("#DisplayTable").show();
          $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
        } else {
          $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");

          hideImage();

          clearInterval(interval); //if last then clearing time interval and calling the function again 
        }

        $(".hidden:lt(10)").removeClass("hidden"); // this one is to hide previous  rows and show next 
      }

      function addTable(tableValue) {
        var $tbl = $("<table />", {
            "class": "table fixed table-bordered"
          }),
          $tb = $("<tbody/>"),
          $trh = $("<tr/>");

        var split = Math.round(tableValue.length / 4);
        for (i = 0; i < split; i++) {
          $tr = $("<tr/>", {
            class: "hidden w3-animate-zoom"
          });

          for (j = 0; j < 4; j++) {
            $.each(tableValue[split * j + i], function(key, value) {
              if (typeof(value) === "number") {
                $("<td/>", {
                  "class": "text-right color" + (j + 1)
                }).html(value).appendTo($tr);
              } else {
                $("<td/>", {
                  "class": "text-left color" + (j + 1)
                }).html(value).appendTo($tr);
              }

            });
          }
          $tr.appendTo($tb);
        }
        $tbl.append($tb);
        $("#DisplayTable").html($tbl);

      }



      function imageFormatter() {

        var images = {
          CounterA: ["CounterA1.jpg", "CounterA2.jpg"]
        }; // This data is dynamic so I want to 

        for (var key in images) {

          var imageList = images[key];
          for (i = 0; i < imageList.length; i++) {
            var img = $('<img />').attr({
              'src': 'Image/' + key + '/' + imageList[i], // this one is displaying Image one below other
              'alt': key + '/' + imageList[i],
              'width': 90 + "%",
              'height': 680
            }).appendTo('#displayImage');
          }

        }
        imgLen = $("#displayImage img").length;
      }
      });
tbody>tr>td {
  white-space: normal;
  border-collapse: collapse;
  font-family: Verdana;
  font-weight: bold;
  font-size: .9em;
}

td:nth-child(2),
td:nth-child(4),
td:nth-child(6),
td:nth-child(8) {
  width: 85px;
  max-width: 85px;
  height: 63px
}

.fixed {
  table-layout: fixed;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden,
.already-shown {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="DisplayTable"></div>
<div id="displayImage" style="display:none">

</div>
<link rel="stylesheet" href="#" onclick="location.href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'; return false;">