html代码放进json数据,用json数据填充html表

好的,在这个解决方案中,我假设您的外部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 ***

&nbsp&nbspCOUNTRY&nbsp&nbspLOCATION&nbsp&nbspBALANCE&nbsp&nbspDATE

//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);

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值