2016-10-21 6 views
2

API рыночных данных обеспечивает доступ к JSON отформатированных данных через гиперссылку, следующим образом:Как получить доступ и использовать данные JSON с внешнего сайта?

{"status":{"code":200,"message":"Success."},"results":[{"symbol":"IBM","timestamp":"2015-06-22T00:00:00-04:00","tradingDay":"2015-06-22","open":160.1176,"high":160.7766,"low":159.6878,"close":160.194,"volume":2445578,"openInterest":null}, 
{"symbol":"IBM","timestamp":"2015-06-23T00:00:00-04:00","tradingDay":"2015-06-23","open":160.8148,"high":162.3333,"low":160.0412,"close":161.044,"volume":3875734,"openInterest":null}, 
... etc ..., 
{"symbol":"IBM","timestamp":"2016-10-20T00:00:00-04:00","tradingDay":"2016-10-20","open":151.28,"high":152.9,"low":151.02,"close":151.52,"volume":4023100,"openInterest":null}]} 

Я пытаюсь узнать, как использовать эти данные; например, представить его в формате таблицы на странице html, как показано ниже. Пока нет радости. Основной вопрос => Как правильно получить доступ, перебрать и форматировать данные для записи/вывода на страницу html?

<!doctype html> 

<html> 
<head> 
</head> 
<body> 

<h1>Example</h1> 
<div id="id01"></div> 

<script> 
var xmlhttp = new XMLHttpRequest(); 
var url = "http://marketdata.websol.barchart.com/getHistory.json?key=[my_api_key#]&symbol=IBM&type=daily&startDate=20150621000000"; 

xmlhttp.onreadystatechange=function() { 
    if (this.status.code == 200 && this.status.message == Success) { 
     myFunction(this.responseText); 
    } 
} 

xmlhttp.open("GET", url, true); 
xmlhttp.send(); 

function myFunction(response) { 
    var arr = JSON.parse(response); 
    var i; 
    var out = "<table>"; 

    for(i = 0; i < arr.length; i++) { 
     out += "<tr><td>" + 
     arr[i].results.symbol + 
     "</td><td>" + 
     arr[i].results.tradingDay + 
     "</td><td>" + 
     arr[i].results.open + 
     "</td><td>" + 
     arr[i].results.high + 
     "</td><td>" + 
     arr[i].results.low + 
     "</td><td>" +        
     arr[i].results.close + 
     "</td><td>" +        
     arr[i].results.volume + 
     "</td></tr>"; 
    } 
    out += "</table>"; 
    document.getElementById("id01").innerHTML = out; 
} 
</script> 

</body> 
</html> 

ответ

2

Вы можете получить доступ к jsonData как к объекту.

Посмотрите на этот пример, чтобы получить информацию о symbol и timestamp вашего примера.

Тогда вам нужно только построить строки html.

var jsonData = {"status":{"code":200,"message":"Success."},"results":[{"symbol":"IBM","timestamp":"2015-06-22T00:00:00-04:00","tradingDay":"2015-06-22","open":160.1176,"high":160.7766,"low":159.6878,"close":160.194,"volume":2445578,"openInterest":null}, 
 
{"symbol":"IBM","timestamp":"2015-06-23T00:00:00-04:00","tradingDay":"2015-06-23","open":160.8148,"high":162.3333,"low":160.0412,"close":161.044,"volume":3875734,"openInterest":null}, 
 
{"symbol":"IBM","timestamp":"2016-10-20T00:00:00-04:00","tradingDay":"2016-10-20","open":151.28,"high":152.9,"low":151.02,"close":151.52,"volume":4023100,"openInterest":null}]} 
 

 

 
function myFunction(response) { 
 
var numResults = response.results.length; //it's an array 
 
for (var i=0; i < numResults; i++) { 
 
    var symbol = jsonData.results[i]["symbol"]; 
 
    var timestamp = jsonData.results[i]["timestamp"]; 
 
    
 
    $("table").append("<tr><td>" + symbol + "</td><td>" + timestamp + "</td></tr>"); 
 
    
 
    } 
 
       
 
    
 
} 
 

 

 
myFunction(jsonData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<table border="1"></table>

+0

Спасибо. Выглядит отлично. Как JSON программно связан с «var jsonData =»? – tj001

+0

@ tj001 Я подделал его (жестко закодированный напрямую), но вместо этого вы должны использовать свой XMLHttpRequest(), как в своем коде. –

0

results вы хотите напечатать массив, так что используйте цикл

{"status":{"code":200,"message":"Success."},"results":[{"symbol":"IBM","timestamp":"2015-06-22T00:00:00-04:00","tradingDay":"2015-06-22","open":160.1176,"high":160.7766,"low":159.6878,"close":160.194,"volume":2445578,"openInterest":null}, 
 
{"symbol":"IBM","timestamp":"2015-06-23T00:00:00-04:00","tradingDay":"2015-06-23","open":160.8148,"high":162.3333,"low":160.0412,"close":161.044,"volume":3875734,"openInterest":null}, 
 
... etc ..., 
 
{"symbol":"IBM","timestamp":"2016-10-20T00:00:00-04:00","tradingDay":"2016-10-20","open":151.28,"high":152.9,"low":151.02,"close":151.52,"volume":4023100,"openInterest":null}]}
<!doctype html> 
 

 
<html> 
 
<head> 
 
</head> 
 
<body> 
 

 
<h1>Example</h1> 
 
<div id="id01"></div> 
 

 
<script> 
 
var xmlhttp = new XMLHttpRequest(); 
 
var url = "http://marketdata.websol.barchart.com/getHistory.json?key=[my_api_key#]&symbol=IBM&type=daily&startDate=20150621000000"; 
 

 
xmlhttp.onreadystatechange=function() { 
 
    if (this.status.code == 200 && this.status.message == Success) { 
 
     myFunction(this.responseText); 
 
    } 
 
} 
 

 
xmlhttp.open("GET", url, true); 
 
xmlhttp.send(); 
 

 
function myFunction(response) { 
 
    var arr = JSON.parse(response); 
 
    var i; 
 
    var out = "<table>"; 
 

 
    for(i = 0; i < arr.length; i++) { 
 
var results_ = arr[i].results; 
 
     for(n=0;n<results_.length;n++){ 
 
out += "<tr><td>" + 
 
     results_[n].symbol + 
 
     "</td><td>" + 
 
     results_[n].tradingDay + 
 
     "</td><td>" + 
 
     results_[n].open + 
 
     "</td><td>" + 
 
     results_[n].high + 
 
     "</td><td>" + 
 
     results_[n].low + 
 
     "</td><td>" +        
 
     results_[n].close + 
 
     "</td><td>" +        
 
     results_[n].volume + 
 
     "</td></tr>"; 
 
} 
 
    } 
 
    out += "</table>"; 
 
    document.getElementById("id01").innerHTML = out; 
 
} 
 
</script> 
 

 
</body> 
 
</html>