如何显示位置在通过XMLHttpRequest访问的JSON文件中的图像?

时间:2018-12-19 07:26:58

标签: html json xmlhttprequest

以下是JSON数据(https://api.data.gov.sg/v1/transport/traffic-images)的示例:

{
  "items": [
    {
      "timestamp": "2018-12-19T15:18:38+08:00",
      "cameras": [
        {
          "timestamp":"2018-12-19T15:17:18+08:00",
          "image":"https://images.data.gov.sg/api/traffic-images/2018/12/d18c7fee-f2a4-454a-b68f-c21dd3c34493.jpg",
          "location": {
            "latitude": 1.29531332,
            "longitude":103.871146
          },
          "camera_id": "1001",
          "image_metadata": {
            "height": 240,
            "width": 320,
            "md5": "230ef16904c20b3108d7b5c378912a4a"
          }
        },
        {
          "timestamp": "2018-12-19T15:17:18+08:00",
          "image": "https://images.data.gov.sg/api/traffic-images/2018/12/2cca04f5-7c76-4887-a683-85f5f2f7e5fa.jpg",
          "location": {
            "latitude": 1.319541067, 
            "longitude": 103.8785627
          },
          "camera_id": "1002",
          "image_metadata": {
            "height": 240,
            "width": 320,
            "md5": "818f64f1362871f28780ee6721c0befa"
          }
        }
      ]
    }
  ]
}

我的html代码:

<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
  function loadDoc() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET","api.data.gov.sg/v1/transport/traffic-images",true); 
    // ...
    xhr.send();
  }
</script>

我对html和ajax还是很陌生,所以如果我错了,请纠正我, 但是时间戳在项目数组中吗?直接从xhr.responseText提取图像是否更好?有办法吗?

基本上,图像链接在显示实时Feed时每20秒就会更改一次。

1 个答案:

答案 0 :(得分:0)

  1. 每个项目都有一个时间戳
  2. 在XHR中使用'json'作为响应类型,然后将数据存储在xhr.response中:

    const xhr = new XMLHttpRequest()
    xhr.open('GET','https://api.data.gov.sg/v1/transport/traffic-images',true)
    xhr.responseType = 'json'
    xhr.onreadystatechange = function() {
      if (xhr.readyState !== 4) return
      const data = xhr.response
      const element = document.getElementById('demo')
      element.innerHTML = ''
      for (let item of data.items) {
        for (let camera of item.cameras) {
          const img = document.createElement('img')
          img.src = camera.image
          element.appendChild(img)
        }
      }
    }
    xhr.send(null)