2016-03-29 1 views
0

Ich möchte eine lokale JSON-Datei von einer HTML-Seite lesen. Aber ich kann die lokale JSON-Datei in der HTML-Seite, die für Chrome und IE funktioniert, nicht lesen. Gibt es eine Möglichkeit, dies ohne Verwendung eines Webservers zu tun?Wie können wir eine lokale JSON-Datei in einer HTML-Seite ohne Server lesen

+0

See zu erhalten Diese Antwort http://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript –

Antwort

0

Angenommen, Sie haben, index.html & sample.json im selben Ordner, Sie dies tun können,

$http.get('sample.json').then(function(response) { 
    console.log(response); 
}); 

natürlich müssen Sie dies von einem Controller laufen, stand alone oder in einer Richtlinie usw.

0

fand ich diese Lösung auf dem Netz, habe ich es nicht ausprobiert, aber nach den Kommentaren sollte es funktionieren

function loadJSON(callback) { 

    var xobj = new XMLHttpRequest(); 
     xobj.overrideMimeType("application/json"); 
    xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file 
    xobj.onreadystatechange = function() { 
      if (xobj.readyState == 4 && xobj.status == "200") { 
      // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode 
      callback(xobj.responseText); 
      } 
    }; 
    xobj.send(null); 
} 

The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of my_data.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it. 

function init() { 
loadJSON(function(response) { 
    // Parse JSON string into object 
    var actual_JSON = JSON.parse(response); 
}); 
}`` 

http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript

-1

Erstellen Sie eine JSON-Datei den folgenden Code verwenden sample.json in einem Übersetzungs Ordner .Dann in Controller genannt, um die Werte in JSON-Datei

$http.get('translation/sample.json').success(function(response){ 
     console.log(response);   
}); 

oder

$.getJSON('translation/sample.json', function(data){ 
    console.log(data); 
}); 
+0

Sie können Ihre Frage bitte bearbeiten, Erklärungen sind für die Gemeinschaft, nicht für mich ;) – GGO

Verwandte Themen