【问题标题】:Calling data from JSON file using AJAX使用 AJAX 从 JSON 文件中调用数据
【发布时间】:2015-07-27 23:47:27
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

  • AJAX 调用完成时i 的值是多少?使用这样的全局变量似乎是个坏主意。
  • 在函数的声明中,参数必须是标识符。 "external-file.json" 不是有效参数。
  • @light 在回答中显示正确的方法。
  • 要充分给出答案,我们需要先了解问题。这个问题的措辞方式,我认为没有人知道它真正在问什么。在 OP 更清楚地说明他所面临的错误之前,我们只能指出他的代码中明显的小错误。
  • @light This is my web app. 这些卡片应该显示我在.json 文件中的值。如您所见,他们没有。那是我的问题。

标签: javascript ajax json parsing


【解决方案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);

【讨论】:

  • 我应该给 url 字符串“external-file.json”的值吗?
  • 这就是你在这里所做的:getViaAjax("external-file.json", yourLoadingFunction)
  • @ArielHalilajAl 请编辑您问题中的代码,并告诉我们您所说的“它不起作用”是什么意思。 stackoverflow.com/help/mcve
  • 我正在制作一个网络应用程序。 Flashcards。我正在尝试将值存储在外部文件中,并仅在需要时调用它们以节省加载时间。
【解决方案2】:

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

有两个文件

  1. data.json
  2. index.html

data.json

[{ “身份证”:1, “价值”:“富” }, { “身份证”:2, “价值”:“酒吧” }]

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 数组中每个对象的列表项

【讨论】:

  • 我认为这与我正在尝试做的事情大不相同。我正在制作flashcards web app,我想做的是将wordsexplanation 的值存储在外部文件中,以节省页面加载时间。
  • @ArielHalilajAl 它实际上与您对代码所做的事情并没有“非常不同”,但它与您添加的描述所说的您想要完成的事情不同。我很奇怪您正尝试使用 xhr 写入本地文件。通过阅读您的代码,我假设您只是想从文件中读取数据。写入最终用户机器上的任意文件对您来说不是一个可行的解决方案。我的建议是您在资源的字符串化版本中使用 localStorage API 和内容,以便您可以在 json 中使用它。
  • ...可能比将资源文件填充到 IndexedDB 并让 it 与文件系统接口以执行文件 io 更好。我有一段时间不需要使用它了,所以您可能需要研究您想要支持的浏览器中的实现。
  • 代码是由 Reddit 上的某个人编写的,我向他寻求帮助。我只是想从文件中读取数据,但我变得越来越困惑。您能提供您认为最简单的解决方案吗?
  • @Ariel ...如果您想从外部 .json 文件中读取数据,我的示例将向您展示如何做到这一点。如果您想写入 到外部 .json 文件 - 看起来好像是这样 - 您的任务会变得更加复杂。您没有(也不应该)从浏览器直接控制文件系统。 HTML5 Filesystem API 由 Google 启动,作为一种允许应用程序在文件系统上使用沙箱来执行文件 io 的方法,但他们的想法从未实现(主要是因为已经存在更好的替代方案)[继续]
猜你喜欢
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多