2017-05-26 56 views
-2

我對html和css很滿意,但絕對沒有使用javascript的經驗。如何在html中顯示Json API數據?

我想要顯示從該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>

謝謝:)

+0

https://stackoverflow.com/help/how-to-ask – tech2017

+0

HTTPS ://developer.mozilla.org/en-US/docs/AJAX – Thiatt

+0

@sloane一旦你已經顯示出一些努力。一旦你已經證明你已經真正嘗試過自己,這是我們的工作。你沒有在這裏做過。 – Carcigenicate

回答

1

這段代碼是用Jquery

我建議你學習一些關於ajax

編輯:我有更新我的答案,以適應你的情況。工作小提琴here

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

的Javascript

<script> 

$(document).ready(function(){ 

    $.ajax({ 
      url: "http://api.travelpayouts.com/data/routes.json?token=PutHereYourToken", 
      type: 'GET', 
      dataType: 'json', 
      success: function(res) { 
       $('#result').html(res) 
      } 
     }); 

}) 

</script> 

不要忘記,包括jQuery和在HTML的頭部分的JavaScript代碼。

+3

請注意,JQuery不需要使用AJAX,但它確實簡化了它的使用。 – Carcigenicate

+1

是的,很好的提醒。 :) –

+0

感謝它很好:) – sloane

2

這裏的工作的例子,不使用jQuery

// Callback to run when data is ready 
function reqListener() { 
    // Parse the JSON text to an object so we can get just one property 
    var data = JSON.parse(this.responseText); 
    // Append that value to the DOM. 
    document.querySelector("#demo").innerHTML = data.body; 
} 

// Create a new ajax requst 
var oReq = new XMLHttpRequest(); 
// Fire callback on load event 
oReq.addEventListener("load", reqListener); 
// Create the connection to our API 
oReq.open("GET", "https://jsonplaceholder.typicode.com/posts/1"); 
// Fire the request 
oReq.send(); 

瞭解更多關於AJAX here,看看這方面的工作fiddle