【发布时间】:2019-04-28 20:41:16
【问题描述】:
我使用 XMLHttpRequest 创建了一个加载函数来读取 JSON 文件,并将其写入我的 HTML 文件中的 div 中。 (如果你愿意,这里有代码)
function load(file){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
// console.log(this);
if(this.readyState == 4 && this.status == 200) {
$("#personnage").empty();
if(this.response.id == 1){
$('#personnage').append(`<p>Sexe : ${this.response.sexe} </p>`);
$('#personnage').append(`<p>Nom : ${this.response.nom} </p>`);
$('#personnage').append(`<p>Prenom : ${this.response.prenom} </p>`);
$('#personnage').append(`<p>Race : ${this.response.race} </p>`);
$('#personnage').append(`<p>Age : ${this.response.age} </p>`);
$('#personnage').append(`<p>Hobbies : ${this.response.hobbies} </p>`);
$('#personnage').append(`<p>Metier : ${this.response.metier} </p>`);
$('#personnage').append(`<p>Pouvoir/spécialisation : ${this.response.pouvoir} </p>`);
$('#personnage').append(`<p>Histoire : ${this.response.histoire} </p>`);
} else if (this.response.id == 2) {
$('#personnage').append(`<p>Sexe : ${this.response.sexe} </p>`);
$('#personnage').append(`<p>Nom : ${this.response.nom} </p>`);
$('#personnage').append(`<p>Prenom : ${this.response.prenom} </p>`);
$('#personnage').append(`<p>Race : ${this.response.race} </p>`);
$('#personnage').append(`<p>Age : ${this.response.age} </p>`);
$('#personnage').append(`<p>Hobbies : ${this.response.hobbies} </p>`);
$('#personnage').append(`<p>Metier : ${this.response.metier} </p>`);
$('#personnage').append(`<p>Forces : ${this.response.forces} </p>`);
$('#personnage').append(`<p>Faiblesses : ${this.response.faiblesses} </p>`);
$('#personnage').append(`<p>Objets : ${this.response.objets} </p>`);
$('#personnage').append(`<p>Pouvoir/spécialisation : ${this.response.pouvoir} </p>`);
$('#personnage').append(`<p>Histoire : ${this.response.histoire} </p>`);
} else {
alert("Erreur fichier non reconnu !");
}
} else if (this.readyState == 4 && this.status == 404) {
console.log("Erreur")
}
}
xhr.open("GET", file, true);
xhr.responseType = "json"
xhr.send();
}
但我希望用户使用<input type="file" />,而不是使用其他网站来存储 JSON(如 http://myjson.com/),但我不知道该怎么做。 (对不起,如果我犯了一些错误,英语不是我的主要语言)
【问题讨论】:
标签: javascript jquery json xmlhttprequest