想实现一个字符笔画类的小应用,笔画信息准备放在一个json文件里,用同文件夹内的html读取json以作为数据来源。以下两种方式虽然都可以实现,但需求服务器环境,如果希望能在本地直接运行html文件,那还是直接把数据写在html文件里更为方便一些。
jquery的实现
$(document).ready(function() {
// 使用 jQuery 的 $.getJSON 方法读取 hanzi.json
$.getJSON("hanzi.json")
.done(function(data) {
// 遍历所有字符并添加到页面
$.each(data.characters, function(index, item) {
$("#charContainer").append(
$("<button>").addClass("char").text(item.char)
);
});
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error("读取文件时出错:", textStatus, errorThrown);
$("#charContainer").text("加载汉字失败,请检查控制台。");
});
});
fetch方法
//读取json文件
fetch('hanzi.json')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
console.log('成功读取hanzi.json文件内容:');
console.log(data);
})
.catch(error => {
console.error('读取文件时出错:', error);
});