好的,在这个解决方案中,我假设您的外部json文件名为'example.json'
你的外部文件应该是这样的
示例.json:
[
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
]
html保持不变,脚本标记中所做的所有更改都保持不变。我把功能分成两个新功能。第一个函数(get_json_data)从外部json文件获取json数据。第二个函数(append_json)将数据追加到表中。
我在整个代码中添加了注释来解释所有的工作。如果你有任何问题或不清楚的地方,请告诉我。
以下是HTML文件的代码:
*** OTHER STUFF HERE ***
|   COUNTRY |   LOCATION |   BALANCE |   DATE |
|---|
//first add an event listener for page load
document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load
//this function is in the event listener and will execute on page load
function get_json_data(){
// Relative URL of external json file
var json_url = 'example.json';
//Build the XMLHttpRequest (aka AJAX Request)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {//when a good response is given do this
var data = JSON.parse(this.responseText); // convert the response to a json object
append_json(data);// pass the json object to the append_json function
}
}
//set the request destination and type
xmlhttp.open("POST", json_url, true);
//set required headers for the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// send the request
xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
}
//this function appends the json data to the table 'gable'
function append_json(data){
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '
' + object.COUNTRY + '' +'
' + object.LoC + '' +'
' + object.BALANCE + '' +'
' + object.DATE + '';table.appendChild(tr);
});
}
2241

被折叠的 条评论
为什么被折叠?



