javascript - 根据 getJSON 数据的响应显示图像

标签 javascript jquery arrays json

我是 Web 开发新手,我正在尝试弄清楚如何根据 getJSON 的响应显示图像。接收的数据来自 REST API。然后数据存储在 2 个数组中:湿度数组和日期数组。 Humid 包含字符串形式的湿度。然后将湿数组转换为整数数组-humid_final。我想知道如何根据 humd_final 数组中的特定值在屏幕上显示特定图像。

如果humid_final数组中的最新条目= 50,则显示图像A。否则显示图像B。(其中图像A、B是本地存储的静态图像)。

$(function updat() {
  var url = "https://xpm4zyor39.execute-api.us-west-2.amazonaws.com/prod/entries";
  var humid = [],
    date = [],
    humid_final = []

  $.getJSON(url, function (json) {

    $(json['Items']).each(function(i, data) {
      //Store indicator name
      
      // fill the date array
      humid.push(data.humidity);
      // fill the string data array 
      date.push(data.Date);
    });

    console.log(date);
    // query send string that we need to convert into numbers
    for (var i = 0; i < humid.length; i++) {
      if (humid[i] != null) {
        humid_final.push(parseFloat(humid[i]))
      } else {
       humid_final.push(null)
      };
    }

    var chart = new Highcharts.Chart({
      chart: {
        type: 'spline',
        renderTo: 'container'
      },
      title: {
        text: 'indicatorName'
      },
      tooltip: {
        valueDecimals: 2,
        pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}%</b><br/>'
      },
      plotOptions: {
        series: {
          marker: {
            enabled: false
          }
        }
      },
      subtitle: {
        text: 'Source: World Bank Data'
      },
      xAxis: {
        categories: date //.reverse() to have the min year on the left 
      },
      series: [{
        name: 'humidity',
        data: humid_final //
      }]
    });

  }); //getJSON method
  setTimeout(updat, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src= "opendataAPI.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

最佳答案

你就快到了。为 html 中的图像标签指定一个 id 并使其指向标准图像 imageB,如 <img id="changingImage" src="./images/imageB.png" />

那么让我们尝试翻译这个...

If the latest entry in humid_final array= 50 display image A. Else display image B.

进入 JavaScript:

if (humid_final[humid_final.length-1] == 50) {
    document.getElementById('changingImage').src="./images/imageA.png";
}

关于javascript - 根据 getJSON 数据的响应显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45762003/

相关文章:

javascript - ajaxError() 在 $.ajax 错误处理程序之后执行

jquery - css 图像一起移动而不是单独移动

javascript - 如何使用其他对象中的值创建对象?

javascript - 删除元素前后的文本和其他元素

jquery - 是否可以将 jQuery 调整大小限制为 x 或 y Axis ,例如拖动约束?

python - 将值(0 除外)从数组 2 复制到数组 1

php - 多维数组的排序和分解

javascript - Colorbox 插件仅适用于我首先单击的第一个链接。?

javascript - 从 Flask 服务器获取音频并在 React 上以可播放的格式显示音频

javascript - JS : How to detect whether cursor is in textfield