如何加载来自阿贾克斯的文件的JSON对象? [英] How do i load a JSON object from a file with ajax?

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

问题描述

我是新来的JavaScript,并使用JSON来传输数据。

I am new to javascript and using JSON to transfer data.

我需要什么在我的HTML页面,阅读与阿贾克斯的文件只包含一个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吗?或者是有可能加载了JSON文件使用Ajax?

do I need jquery too? or is it possible to load that JSON-file with ajax?

是它在不同的浏览器有什么不同?

is it different on different browsers?

推荐答案

您不需要任何库,一切都在香草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);
});

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

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