JavaScript原生语法实现用Ajax对JSON数据的调用
jQuery写多了把原生语法忘记得一干二净,因为这个项目中未使用jQuery库,所以用了原生js实现,记录下来做个备注。
//Get ajax data
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
getJSON('https://xxxx.json',
function(err, data) {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
Object.keys(data).forEach(function (key){
//console.log(data[key]);
Array.prototype.forEach.call(document.getElementsByClassName("data-" + key), function(element) {
// Use `element` here
element.innerHTML = data[key];
});
});
}
});