如何在html中显示Json API数据?

时间:2017-05-26 19:56:34

标签: javascript html json

我对html和css非常好,但绝对没有使用javascript的经验。

我想将从此API收到的日期显示到html页面

http://api.travelpayouts.com/data/routes.json?token=PutHereYourToken

这就是我到目前为止没有任何成功的尝试。



var getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
      } else {
        reject(status);
      }
    };
    xhr.send();
  });
};

getJSON('https://api.travelpayouts.com/data/routes.json?token=mytoken').then(function(data) {
    alert('Your Json result is:  ' + data.result); 

    result.innerText = data.result; 
}, function(status) { 
  alert('Something went wrong.');
});

<body>
<div class="container">
<div id="result" style="color:red"></div>
</div>
</body>
&#13;
&#13;
&#13;

谢谢:)

2 个答案:

答案 0 :(得分:2)

这是一个不使用jQuery的工作示例

mnu.Click += (o, e) => callback();

详细了解ajax here并查看此工作fiddle

答案 1 :(得分:1)

这段代码是使用Jquery

我建议您稍微了解ajax

编辑:我已更新我的答案以适合您的情况。工作小提琴here

class MySQLDatabase {
    // define class property
    protected $db_config;

    function __construct(){
        if(file_exists(ROOT_PATH.'config.php')){
            // set property value as a result of `json_decode`
            $this->db_config = json_decode(file_get_contents(ROOT_PATH.'config.php'), true);
            // json_decode can fail to return correct json
            // if your file is empty or has some bad contents
            // so we check if we really have a proper array
            if (is_array($this->db_config)) {
                // no need to pass argument to a function
                // as `db_config` property is already set
                $this->open_connection();
            }
        }
    }

    function open_connection() {
        $this->connection = mysqli_connect(
            $this->db_config['DBLocation'], 
            $this->db_config['DBName'], 
            $this->db_config['DBPassword'], 
            $this->db_config['DBUsername']
        );

        if(mysqli_connect_errno()) {
            echo "Connection failed: " . mysqli_connect_error();
        }
    }

的Javascript

<body>
<div class="container">
<div id="result" style="color:red"></div>
</div>
</body>

不要忘记在html的head部分中包含jQuery和javascript代码。