2013-01-17 15 views
15

Sto usando JSON per trasferire i dati.Come caricare un oggetto JSON da un file con ajax?

Cosa mi serve nella mia pagina HTML per leggere un file con Ajax che include solo un oggetto JSON nel mio script?

Ho bisogno anche di jQuery oppure è possibile caricare quel file JSON con Ajax?

È diverso su diversi browser?

+0

jQuery rende Ajax più facile, così come molte altre librerie, ma puoi fare Ajax con Vanilla JS. – nnnnnn

+0

Hai un file statico sul tuo server web che contiene dati JSON serializzati e vuoi leggere quei dati usando AJAX? –

+0

sì, Mike Christensen – rubo77

risposta

47

Non hai bisogno di qualsiasi libreria, tutto è disponibile in vaniglia javascript per recuperare un file JSON e analizzarlo:

function fetchJSONFile(path, callback) { 
    var httpRequest = new XMLHttpRequest(); 
    httpRequest.onreadystatechange = function() { 
     if (httpRequest.readyState === 4) { 
      if (httpRequest.status === 200) { 
       var data = JSON.parse(httpRequest.responseText); 
       if (callback) callback(data); 
      } 
     } 
    }; 
    httpRequest.open('GET', path); 
    httpRequest.send(); 
} 

// this requests the file and executes a callback with the parsed result once 
// it is available 
fetchJSONFile('pathToFile.json', function(data){ 
    // do something with your data 
    console.log(data); 
}); 
+0

Finché non è necessario supportare IE 5 e 6 –

+3

Si potrebbe voler aggiungere '|| httpRequest.status === 0' (per connessioni locali). Questo mi ha davvero incastrato quando ho iniziato a imparare 'xmlhttprequest' –

+2

@JuanMendes L'unica cosa che questo codice dovrebbe supportare versioni precedenti di IE è' var httpRequest = (window.XMLHttpRequest)? Nuovo XMLHttpRequest(): new ActiveXObject (" Microsoft.XMLHTTP ");' Ma a chi importa delle versioni precedenti di IE? ;) –

1

In passato, Ajax era diverso nei vari browser (e lo è ancora se è necessario supportare i browser più vecchi che un buon numero di utenti purtroppo utilizza ancora). Per i browser più vecchi, è necessario disporre di una libreria come JQuery (o il proprio codice equivalente) per gestire le differenze del browser. In ogni caso, per un principiante, potrei raccomandare jQuery per buoni documenti, una semplice API e iniziare rapidamente, anche se MDN è utile anche per JavaScript stesso (e dovresti capire sempre più spesso le API JavaScript/DOM anche se principalmente contare su jQuery).

3

Il modo più efficace è quello di utilizzare semplice JavaScript:

var a = new XMLHttpRequest(); 
a.open("GET","your_json_file",true); 
a.onreadystatechange = function() { 
    if(this.readyState == 4) { 
    if(this.status == 200) { 
     var json = window.JSON ? JSON.parse(this.reponseText) : eval("("+this.responseText+")"); 
     // do something with json 
    } 
    else alert("HTTP error "+this.status+" "+this.statusText); 
    } 
} 
a.send(); 
+0

Questo codice funziona, ma attenzione un percorso errato risulterà in "NS_ERROR_DOM_BAD_URI: accesso a URI limitato negato" facendo sembrare che il codice non funzioni. –

1

Preferisco usare jjery ajax. Jquery rende molto più facile vivere.

Quello che per esempio può fare sul server lato è, suppongo che voi state usando PHP:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){ 
    // if it's an ajax request 

    $json['success'] = 1; 
    $json['html'] = '<div id="test">..[more html code here].. </div>'; 
    echo json_encode($json); 
}else{ 
    // if it's an non ajax request 


} 

Sul lato client è possibile eseguire le seguenti operazioni utilizzando jQuery Ajax:

$.ajax({ 
      type: "POST", 
      url: "[your request url here]", 
      data: { name: "JOKOOOOW OOWNOOO" }, 
      complete: function(e, xhr, settings){ 
       switch(e.status){ 
        case 500: 
        alert('500 internal server error!'); 
        break; 
        case 404: 
         alert('404 Page not found!'); 
        break; 
        case 401: 
         alert('401 unauthorized access');  
        break;  
       } 
      }   
     }).done(function(data) { 
      var obj = jQuery.parseJSON(data) 

      if (obj.success == 1){ 

        $('div#insert_html_div').html(obj.html); 

      }else if (obj.error == 1){ 


          } 


      // etc 

     }); 
+0

Non è la risposta, ma vale ancora la pena menzionarla come alternativa – rubo77

Problemi correlati