Reputation: 4612
This is a file (data.json) containing data formated in JSON :
{
[
{"nom" : "marteau" , "desc" : "pour en enfoncer des clous" , "qte" : "87" , "prix" : "9"},
{"nom" : "cle de 12" , "desc" : "pour les boulons du camion" , "qte" : "25" , "prix" : "12"}
]
}
I try to parse these data in JavaScript this way :
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title> catalogue outillage </title>
<script type="text/javascript" src="oXHR.js"></script>
<script type="text/javascript">
function request(callback) {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
callback(xhr.responseText);
}
}
xhr.open("GET", "data.json", true);
xhr.send();
}
function readData(oData) {
var catalogue = JSON.parse(oData);
document.getElementById("nom").innerHTML = catalogue[0].nom;
document.getElementById("desc").innerHTML = catalogue[0].desc;
document.getElementById("qte").innerHTML = catalogue[0].qte;
document.getElementById("prix").innerHTML = catalogue[0].prix;
}
</script>
</head>
<body>
<form>
<label>Name</label> : <label id = "nom"></label><br>
<label>Description</label> : <label id = "desc"></label><br>
<label>Quantité</label> : <label id = "qte"></label><br>
<label>Prix</label> : <label id = "prix"></label><br>
<button onclick="request(readData)">Afficher json</button>
</form>
</body>
</html>
Unfortunately, xhr.responseText seem to be void.
@epascarello I receive this message in developer console : SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
@ShanRobertson I removed the first set of curly braces. But that doesn't work.
I've found the mistake : I removed the first set of form tag
Thanks for all
Upvotes: 2
Views: 106
Reputation: 2742
Your JSON isn't valid. You just need to remove the first set of curly braces.
[
{
"nom": "marteau",
"desc": "pour en enfoncer des clous",
"qte": "87",
"prix": "9"
},
{
"nom": "cle de 12",
"desc": "pour les boulons du camion",
"qte": "25",
"prix": "12"
}
]
Other than that your code looks fine.
Upvotes: 3