2012-05-07 15 views

risposta

9

Un esempio come fare questo potrebbe essere:

<html> 
<head> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 
<script type="text/javascript"> 
    $(function(){ 
     $.getJSON('names.json',function(data){ 
      console.log('success'); 
      $.each(data.employees,function(i,emp){ 
       $('ul').append('<li>'+emp.firstName+' '+emp.lastName+'</li>'); 
      }); 
     }).error(function(){ 
      console.log('error'); 
     }); 
    }); 
</script> 
</head> 
<body> 
    <ul></ul> 
</body> 
</html> 
5

Nel codice jQuery, si dovrebbe avere la proprietà employees.

data.employees[0].firstName 

Quindi sarebbe come questo.

<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> 
</head> 
<body> 
<script type="text/javascript"> 
    $.getJSON("names.json", function(data) { 
     console.log(data); 
     $('body').append(data.employees[0].firstName); 
    }); 
</script> 
</body> 
</html> 

Naturalmente avrete bisogno che la proprietà per la versione non jQuery troppo, ma avresti bisogno di analizzare la risposta JSON prima.

Ricorda inoltre che document.write sta distruggendo l'intera pagina.


Se hai ancora problemi, provare la piena $.ajax richiesta invece del $.getJSON involucro.

$.ajax({ 
     url: "names.json", 
     dataType: "json", 
     success: function(data) { 
      console.log(data); 
      $('body').append(data.employees[0].firstName); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      console.log('ERROR', textStatus, errorThrown); 
     } 
    }); 

http://api.jquery.com/jquery.ajax/

+0

hi cliffs, ancora non funziona per me. Puoi pubblicare l'intero codice? La sceneggiatura era in testa, ma ora è nel corpo e non ha funzionato. =/ – GarouDan

+0

@GarouDan: Non sei sicuro di cosa intendi quando dici che non funziona. Il callback è invocato? Stai riscontrando errori nella console? –

1

Se si desidera utilizzare PHP.

<?php 
    $contents = file_get_contents('names.json'); 
?> 
<script> 
    var names = <?php echo $contents; ?> 
    var obj = JSON.parse(names); 

    //use obj 
</script> 

Opzionalmente, usarlo ASYNC:

<script> 
    $(document).ready(function(){ 
     $.get("get_json.php?file=names",function(obj){ 
      //use obj here   
     },'json'); 
    }); 
</script> 

Il PHP:

<?php 
    $filename = $_GET['file'] . '.json'; 
    $data['contents'] = file_get_contents($filename); 
    echo json_encode($data); 
?> 
+0

Il file contiene già json, perché json_encode cosa è già json? Poteva solo ottenere dei nomi.json direttamente senza l'ultimo wrapper php. – ccKep

+0

Soluzione interessante xbonez. Proverò un po 'usando jQuery e javascript, ma probabilmente questo risolve anche il mio problema. – GarouDan

+0

thx xbonez, terrò a mente anche questa soluzione. – GarouDan

6

Il file JSON non contiene JSON valido. Prova invece il seguente.

{ 
    "employees": 
    [ 
     { 
      "firstName": "Anna", 
      "lastName": "Meyers" 
     }, 
     { 
      "firstName": "Betty", 
      "lastName": "Layers" 
     }, 
     { 
      "firstName": "Carl", 
      "lastName": "Louis" 
     } 
    ] 
} 

Si dovrebbe quindi vedere una risposta. Scopri http://jsonlint.com/

+0

oh. sì. ora funziona ^^. Grazie mille. Ero cosa il problema è nel codice jquery. – GarouDan

+0

+1 Il JSON non valido è andato subito sopra la mia testa. –

3

si può semplicemente includere un file JavaScript nel codice HTML che dichiari l'oggetto JSON come variabile. Quindi puoi accedere ai tuoi dati JSON dal tuo ambito Javascript globale utilizzando, ad esempio, data.employees.

index.html:

<html> 
<head> 
</head> 
<body> 
    <script src="data.js"></script> 
</body> 
</html> 

data.js:

var data = { 
    "employees": [{ 
    "firstName": "Anna", 
    "lastName": "Meyers" 
    }, { 
    "firstName": "Betty", 
    "lastName": "Layers" 
    }, { 
    "firstName": "Carl", 
    "lastName": "Louis" 
    }] 
} 
+0

È necessario aggiungere questa dichiarazione al file data.js: "" "" module.exports = data; "" "" Altrimenti non sarà possibile importare il valore della variabile di dati in nessun altro file tramite data.js. –

Problemi correlati