如何使用 ajax 从文件加载 JSON 对象? [英] How do I load a JSON object from a file with ajax?

查看:33
本文介绍了如何使用 ajax 从文件加载 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JSON 传输数据.

I am using JSON to transfer data.

在我的 HTML 页面中需要什么才能使用 Ajax 读取仅在我的脚本中包含一个 JSON 对象的文件?

What do I need in my HTML page to read a file with Ajax that only includes one JSON object into my script?

我是否也需要 jQuery,或者是否可以使用 Ajax 加载该 JSON 文件?

Do I need jQuery too, or is it possible to load that JSON file with Ajax?

在不同的浏览器上有什么不同吗?

Is it different on different browsers?

推荐答案

你不需要任何库,一切都可以在 vanilla javascript 中获取 json 文件并解析它:

You don't need any library, everything is available in vanilla javascript to fetch a json file and parse it :

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);
});

这篇关于如何使用 ajax 从文件加载 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆