透過js繫結資料到html網頁是前端工程常用的方法,常用的資料集格式有JSON及XML,以下說明如何實作:
XML
XML資料集
< ?xml version='1.0' ?>
< doc>
< dataset>
< data1>data1< /data1>
< data2>data2< /data2>
< data3>data3< /data3>
< /dataset>
< dataset>
< data1>data1< /data1>
< data2>data2< /data2>
< data3>data3< /data3>
< /dataset>
< dataset>
< data1>data1< /data1>
< data2>data2< /data2>
< data3>data3< /data3>
< /dataset>
< /doc>
透過jquery ajax來把外部xml資料讀進來進行處理
$.ajax({
url: 'data.xml',
type: 'GET',
dataType: "xml",
success: function(data) {
//get xml data
var itemSet = $(data).find('dataset');
//read each data
itemSet.each(function(){
var data1 = $(this).find('title').text(),
data2 = $(this).find('url').text(),
data2 = $(this).find('image').text();
//do something with data
});
})
不透過JQuery讀取xml資料集
var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers except IE
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE
xhr.open('GET', 'data.xml', false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
var items = xhr.responseXML.getElementsByTagName('name');
var output = '< ul>';
for (var i=0; i<items.length; i++) output += '< li>' + items[i].firstChild.nodeValue + '< /li>';
output += '< /ul>';
var div = document.getElementById('update');
div.innerHTML = output;
}
}
xhr.send();
JSON
JSON資料集
[
{
"data1": "data1",
"data2": "data2",
"data3": "data3"
},
{
"data1": "data1",
"data2": "data2",
"data3": "data3"
},
{
"data1": "data1",
"data2": "data2",
"data3": "data3"
}
]
透過JQuery ajax讀取json資料集
$.ajax({
url: "data.json",
type: "GET",
dataType: "JSON",
success: function(data){
var json = $.parseJSON(data);
for (var $k in data) {
var data1 = data[$k]['data1'],
data2 = data[$k]['data2'],
data2 = data[$k]['data3'];
//do something with data
}
}
})
不透過JQuery讀取json資料集
var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers except IE
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE
xhr.open('GET', 'data.json', false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
var items = JSON.parse(xhr.responseText);
var output = '< ul>';
for (var key in items) {
output += '< li>' + items[key].name + '</li>';
}
output += '< /ul>';
document.getElementById('update').innerHTML = output;
}
}
xhr.send();
資料來源:
w3epic.com