如何在Ajax请求上生成一次div以获取数据,然后如何在下一个Ajax请求上仅更新div中的数据?

时间:2018-07-24 12:11:02

标签: javascript jquery html ajax monitoring

嗨,我正在尝试使用来自ajax请求的数据填充div,这个想法是使用Ajax从多个传感器获取温度,并且对于每个传感器温度数据,我想要一个单独的div列,并在文档中添加。准备好我要使用ajax get一次将带有div列的主页面div弹出来获取结果,但是在那之后,我想每隔10秒再次使用ajax来更新数据,但是我怎么做呢?再次数据?由于有什么原因,当我尝试制作一个过滤器以显示/隐藏特定位置的div时,我现在无法正常工作。

$(document).ready(function(){


      var menu_list = [];
      var tr_str = [];
      var temp_int= [];

      $.ajax({
          url: 'getData.php',
          type: 'get',
          dataType: 'JSON',
          success: function(response){
              var len = response.length;
              for(var i=0; i<len; i++){
                  var location = response[i].location;
                  temp_int[i] = response[i].temp_int;
                  var temp = response[i].temp;
                  var hum = response[i].hum;
                  var dew = response[i].dew;

                  tr_str[i] = "<div id='locc" + i + "' class='location'>" +
                      "<span class='title'>" + location + "</span>" +
                      "<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " &degC</span></div>" +
                      "<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
                      "<div><span>Punkt rosy: </span><span>" + dew + " &degC</span></div>" +
                      "</div>";

                  menu_list[i] = "<label for='loc" + i + "'>" +
                      "<input type='checkbox' id='loc" + i + "' checked='checked'/>" +
                      "<span class='css-checkbox'></span>" +
                      "<p>" + location + "</p>" +
                      "</label>";

              }

              $("#nav").append(menu_list);
              $("#data").html(tr_str);

              for(var i=0; i<len; i++){
                if (temp_int[i] >= 250) {
                $(".temp" + i).css("background-color", "#ff0000");
              }
              else if (temp_int[i] >= 235) {
                $('.temp' + i).css("background-color","#f1c40f");
              }
              else {
                $('.temp' +i).css("background-color","#3498db");
              }
            }



          }
      });


      $("#loc1").change(function () {
          if (this.checked){
            $("#locc1").show(!this.checked);
          }else {
            $("#locc1").hide(!this.checked);
          }
      });
    });

  setTimeout(fetchdata,5000);



function fetchdata(){

  var tr_str = [];
  var temp_int= [];

  $.ajax({
      url: 'getData.php',
      type: 'get',
      dataType: 'JSON',
      cache: false,
      success: function(response){
          var len = response.length;
          for(var i=0; i<len; i++){
              var location = response[i].location;
              temp_int[i] = response[i].temp_int;
              var temp = response[i].temp;
              var hum = response[i].hum;
              var dew = response[i].dew;

              tr_str[i] = "<div id='locc" + i + "' class='location'>" +
                  "<span class='title'>" + location + "</span>" +
                  "<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " &degC</span></div>" +
                  "<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
                  "<div><span>Punkt rosy: </span><span>" + dew + " &degC</span></div>" +
                  "</div>";

          }


          $("#data").html(tr_str);

          for(var i=0; i<len; i++){
            if (temp_int[i] >= 250) {
            $(".temp" + i).css("background-color", "#ff0000");
          }
          else if (temp_int[i] >= 235) {
            $('.temp' + i).css("background-color","#f1c40f");
          }
          else {
            $('.temp' +i).css("background-color","#3498db");
          }
        }

      },
      complete:function(){
        setTimeout(fetchdata,5000);
      }

  });
}



function openNav() {
			document.getElementById("nav").style.width = "350px";
      document.getElementById("data").style.marginLeft = "350px";
		}

		function closeNav() {
			document.getElementById("nav").style.width = "0";
      document.getElementById("data").style.marginLeft = "0";
		}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="lib/style.css">
</head>
<body>

  <div id="nav" class="menu">
		<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
		<button>Uncheck all</button>
	</div>

  <div class="nav-wrapper">
		<span onclick="openNav()">&#9776;</span>
	</div>


  <div id="data" class="wrapper"></div>

   
</body>
</html>

您可以看到我再次使用了几乎相同的Ajax请求,是否有办法首先获取数据并生成数据的div,然后仅每10秒获取一次数据并仅在不重新生成的情况下进行更新divs?

我在想,我现在所拥有的只是使该工具无法工作

var $checkboxes = $("#nav :checkbox");
		var $button = $("#nav button");
		
		function allChecked(){
		  return $checkboxes.length === $checkboxes.filter(":checked").length;
		}
		
		function updateButtonStatus(){
		  $button.text(allChecked()? "Uncheck all" : "Check all");
		}
		
		function handleButtonClick(){
		  $checkboxes.prop("checked", allChecked()? false : true)
		}
 
		$button.on("click", function() {
		  handleButtonClick();
		  updateButtonStatus();
		  checking();
		});

		$checkboxes.on("change", function(){
		  updateButtonStatus();
		});
		
		function openNav() {
			document.getElementById("nav").style.width = "250px";
		}

		function closeNav() {
			document.getElementById("nav").style.width = "0";
		}	

		function checking() {
			var temps = <?php echo json_encode($temps); ?>;  //I know this is wrong I would change the loop iteration but it is not working even for one static element when I change it.
			$.each( temps, function( index, value ){						

						$('#loc'+index).change(function () {               
						if( this.checked ) {
							$('#locc'+index).show(!this.checked);
						} else {
							$('#locc'+index).hide(!this.checked);
						}         
						}).change();
		});}

这是我使用Ajax获取的php文件代码:

<?php

require 'lib/locations.php';
		$search = array('STRING: ', '"');
		$search2 = array('INTEGER: ', '"');
		$replace = array('','');
		$return_arr = array();

for ($i = 0; $i < $c; $i++) {

		$temp_int = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.3.1.0");
		$temp_int = str_replace($search2,$replace,$temp_int);

		$temp = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.1.0");
		$temp = str_replace($search,$replace,$temp);
		$hum = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.2.0");
		$hum = str_replace($search,$replace,$hum);
		$dew = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.3.0");
		$dew = str_replace($search,$replace,$dew);
		$loc = $location[$i];

		$return_arr[] = array("location" => $loc,
													"temp_int" => $temp_int,
													"temp" => $temp,
													"hum" => $hum,
													"dew" => $dew);

		}

echo json_encode($return_arr);

?>

生成的数据是一个包含一个整数和字符串的数组

类似这样的东西:

var response =[{
"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
},
{"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
}, etc.]

0 个答案:

没有答案