How do I load a JSON object from a file with ajax?
I am using JSON to transfer data.
What do I need in my HTML page to read a file with Ajax that only includes one JSON object into my script?
Do I need jQuery too, or is it possible to load that JSON file with Ajax?
Is it different on different browsers?
你不需要任何库,一切都可以在香草JavaScript中获取一个JSON文件并解析它:
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);
});
最有效的方法是使用普通的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();
In the past, Ajax was different in different browsers (and still is if you need to support older browsers which a good number of users are unfortunately still using). For older browsers, you would need a library like JQuery (or your own equivalent code) to handle the browser differences. In any case, for a beginner, I might recommend jQuery for good docs, a simple API, and getting started quickly, though MDN is helpful for JavaScript itself too (and you really should increasingly get to understand JavaScript/DOM APIs even if you primarily rely on jQuery).
链接地址: http://www.djcxy.com/p/74356.html下一篇: 如何从ajax文件加载JSON对象?