Come posso ottenere solo il nome dal file JSON. Anche il codice è perfettamente funzionante per ottenere i dati da "file.json", cioè questo non è certo il problema.Ottieni un solo elemento dalla matrice di oggetti in JSON
JavaScript:
var data = [];
function getName() {
//what should I write here to get only name from the first object i.e. John
//with this: data[0].name I am getting error!
}
var xhttp;
if(window.XMLHttpRequest)
xhttp = new XMLHttpRequest();
else
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4) {
data = JSON.parse(xhttp.responseText);
getName();
}
}
xhttp.open("GET","file.json",true);
xhttp.send();
"file.json" - JSON:
[
{
"name":"John",
"city":"London"
},
{
"name":"Maria",
"city":"Rome"
}
]
(Invece di 'onreadystatechange' e' readyState', puoi semplicemente usare 'onload'.) – Rudie
Funziona bene per me, come in, nessun errore. Qual è il tuo errore? https://jsfiddle.net/rudiedirkx/0xf62ny6/ registra l'intero oggetto dati e quindi 'data [0] .name' – Rudie
Qual è l'errore? Perché stai usando una variabile globale invece di passare il valore alla funzione? –