使用AJAX从JSON文件调用数据

时间:2015-07-27 23:47:28

标签: javascript ajax json parsing

我正在尝试使用AJAX从我的JSON文件加载一些数据。该文件名为external-file.json。这是代码,它包含了与数据加载无关的其他部分。我不确定的部分是从getViaAjax功能开始的。我似乎无法找到我的错误。

function flip(){
    if(vlib_front.style.transform){
        el.children[1].style.transform = "";
        el.children[0].style.transform = "";
    } else {
        el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
        el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
    }
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');

el.addEventListener('click', flip);

var word = null; var explanation = null;

var i=0;

function updateDiv(id, content) {
    document.getElementById(id).innerHTML = content;
    document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])

function counter (index, step){
    if (word[index+step] !== undefined) {
        index+=step;
        i=index;
        updateDiv('the-h',word[index]);
        updateDiv('the-p',explanation[index]);
    }      
}

var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
    counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
    counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
    var r = new XMLHttpRequest();
    r.open("GET", "external-file.json", true);
    r.onload = function() {
        if(this.status < 400 && this.status > 199) {

            if(typeof callback === "function")
                callback(JSON.parse(this.response));
        } else {
            console.log("err");// server reached but gave shitty status code}
        };
    }
    r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}

    r.send();
}

function yourLoadingFunction(jsonData) {
    word = jsonData.words;
    explanation = jsonData.explanation;
    updateDiv('the-h',word[i]);
    updateDiv('the-p',explanation[i])
    // then call whatever it is to trigger the update within the page
}

getViaAjax("external-file.json", yourLoadingFunction)

2 个答案:

答案 0 :(得分:1)

正如@light所说,这:

function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
  var r = new XMLHttpRequest();
  r.open("GET", "external-file.json", true);

应该是:

function getViaAjax(url, callback) { // url being the url to external File holding the json
  var r = new XMLHttpRequest();
  r.open("GET", url, true);

答案 1 :(得分:0)

我建立了一个可以分享的快速示例,可以帮助您隔离问题。在您选择的本地http-server中站起来,您应该看到JSON.parse(xhr.response)返回包含两个对象的javascript数组。

有两个文件

  1. data.json
  2. 的index.html
  3. <强> data.json

    
        [{
            "id":1,
            "value":"foo"
        },
        {
            "id":2,
            "value":"bar"
        }]
    
    

    <强>的index.html

    <html>
        <head>
        </head>
        <body onload="so.getJsonStuffs()">
            <h1>so.json-with-ajax</h1>
            <script type="application/javascript">
            var so = (function(){
    
                function loadData(data){
                   var list = document.createElement("ul");
                   list.id = "data-list";
                   data.forEach(function(element){
                       var item = document.createElement("li");
                       var content = document.createTextNode(JSON.stringify(element));
    
                       item.appendChild(content);
                       list.appendChild(item);
                   });
                   document.body.appendChild(list);
               }
    
                var load = function()
                {
                    console.log("Initializing xhr");
                    var xhr = new XMLHttpRequest();
    
                    xhr.onload = function(e){
                        console.log("response has returned");
                        if(xhr.status > 200
                        && xhr.status < 400) {
                            var payload = JSON.parse(xhr.response);
                            console.log(payload);
                            loadData(payload);
                        }
                    }
                    var uri = "data.json";
                    console.log("opening resource request");
                    xhr.open("GET", uri, true);
                    xhr.send();
                }
    
                return {
                    getJsonStuffs : load
                }
            })();
            </script>
        </body>
    </html>
    

    Running会将两个Javascript对象记录到Dev Tools控制台,并向DOM添加一个ul,其中包含data.json数组中每个对象的列表项