首页 > 解决方案 > 如何使用 Vue / Html 脚本处理 json (http-Request)

问题描述

如何处理 json ( https://engelhardt.ocloud.de/index.php/apps/phonetrack/api/getlastpositions/64dda53cc503629cedb5f8c8102708ed ) 以显示属性 (lat,lon, speed, ...) 与 vue / html ?

json内容:

{
  "64dda53cc503629cedb5f8c8102708ed": {
    "Test": {
      "lat": 50,
      "lon": 10,
      "timestamp": 15,
      "batterylevel": 10,
      "satellites": 5,
      "accuracy": 10,
      "altitude": 100,
      "speed": 0,
      "bearing": 0
    }
  }
}

这是我的 index.html 文件,用于显示原始 json 内容:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>
</head>

<body>
<div id="vue-root">
        Json-Raw: {{ jsonraw }}
</div>
</body>

<script>
new Vue({
  el: "#vue-root",
  data: {
    jsonraw: [],
    lat: [],
    lon: []
  },  
  created () {
    this.fetchData()
  },  
  methods: {
    fetchData () {
        fetch('https://engelhardt.ocloud.de/index.php/apps/phonetrack/api/getlastpositions/64dda53cc503629cedb5f8c8102708ed')
          .then(response => {
          this.jsonraw = response.data;
        })        
    }
 }
})
</script>
</html> 

浏览器结果为空:

Json-Raw:[]

出了什么问题?如何访问单个主题,例如 json.lat、json.lon 或 json.speed?

标签: htmlvue.js

解决方案


在您的fetchData()方法中,执行以下操作:

fetchData () {
  fetch('https://engelhardt.ocloud.de/index.php/apps/phonetrack/api/getlastpositions/64dda53cc503629cedb5f8c8102708ed')
    .then(response => response.json()) // This is the important line you should have when using fetch
    .then(data => this.jsonRaw = data)
}

更多阅读可以在这里找到。


推荐阅读