<分区>
我想将 JSON 数据加载到 Javascript 变量中,解析出一些数据,然后将其显示在 HTML 中。
JSON数据取自雅虎金融API http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail
我什至不确定如何将数据放入变量中。一旦我这样做了,我想提取“名称”和“价格”并将它们输出到 HTML 表格中。
<分区>
我想将 JSON 数据加载到 Javascript 变量中,解析出一些数据,然后将其显示在 HTML 中。
JSON数据取自雅虎金融API http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail
我什至不确定如何将数据放入变量中。一旦我这样做了,我想提取“名称”和“价格”并将它们输出到 HTML 表格中。
最佳答案
仅使用 JavaScript:
如果您通过 XMLHttpRequest 请求 WebService URL ,你会遇到 CORS 问题:
XMLHttpRequest cannot load http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
但是,您可以使用 https://crossorigin.me/服务。
然后,您应该请求:« https://crossorigin.me/http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail »。最后,这可以很容易地在 JavaScript 中使用。您不需要使用 jQuery。
我做了一个演示。
像这样:
(function() {
var newXHR;
// Helper function to make XMLHttpRequest without using jQuery or AngularJS $http service.
function sendXHR(options) {
// (Modern browsers) OR (Internet Explorer 5 or 6).
newXHR = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
if (options.sendJSON === true) {
options.contentType = "application/json; charset=utf-8";
options.data = JSON.stringify(options.data);
} else {
options.contentType = "application/x-www-form-urlencoded";
}
newXHR.open(options.type, options.url, options.async || true);
newXHR.setRequestHeader("Content-Type", options.contentType);
newXHR.send((options.type == "POST") ? options.data : null);
newXHR.onreadystatechange = options.callback; // Will executes a function when the HTTP request state changes.
return newXHR;
}
// Call the WebService by using the helper function.
sendXHR({
type: "GET",
url: "https://crossorigin.me/http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail",
callback: function() {
if (newXHR.readyState === 4 && newXHR.status === 200) {
var data = JSON.parse(newXHR.response); // Store the WebServices JSON data to the «data» variable.
var table = document.getElementById("table"); // Get the table.
// Build the HTML table.
var html = "<table><thead>";
html += "<th>Name</th><th>Price</th>";
html += "</thead>";
html += "<tbody>";
for (i = 0; i < data.list.resources.length; i++) {
html += "<tr><td>" + data.list.resources[i].resource.fields.name + "</td><td>" + data.list.resources[i].resource.fields.price + "</td></tr>";
}
html += "</tbody></table>";
table.innerHTML = html;
}
}
});
})();
#table table {
border: solid 1px #CCCCCC;
border-collapse: collapse;
}
#table table td {
border: solid 1px #CCCCCC;
padding: 5px;
}
<div id="table"></div>
此答案的简短版本:
关于javascript - 如何将JSON数据放入变量、解析、输出为HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37101083/