如何将JSON.parse结果存储在父对象中?

时间:2015-08-01 23:21:01

标签: javascript json

我完全难过并尝试了一切...试图制作一个动态创建的元素周期表。我是javascript的新手,对于使用JSON数据非常新。我已经通过StackOverflow解决了很多问题,但似乎无法找到这个问题的答案。

我试图将JSON.parse语句的结果存储为父类对象但它似乎永远不会工作...通过JSON.parse加载JSON数据工作正常但尝试访问不同的数据父方法不起作用。

var Parent_Object  = function() {
     this.parent = this;
     this.element_data;

     this.initElementData = function() {
        var request = new XMLHttpRequest();
        request.open('GET', '<data_location>', true);

        request.onload = function() {
            if (request.status >= 200 && request.status < 400) {
                parent.element_data = JSON.parse(request.responseText);  // trying to store the result as a parent class object (or whatever it would be called)...
                document.getElementById("json_status").innerHTML = "Status: JSON data successfully loaded...";
                document.getElementById("json_status").innerHTML += parent.element_data[0].element_name;  // this works fine, no problem with this!
            } else {
                document.getElementById("json_status").innerHTML = "Status: Couldn't find the JSON data...<br>";
            }

        };

        request.onerror = function() {
            document.getElementById("json_status").innerHTML = "Connection error of some sort...<br>";
        };

        request.send();
    };

    this.laterFunction = function() {
        document.getElementById('json_status').innerHTML = parent.element_data[0].element_name;  // This doesn't work, data is gone!
    };

}

以下是JSON的小片段(警告,其中一些值仍然不正确,以后再修复):

[
    {
            "element_name" : "Helium" ,
            "atomic_number" : 2,
            "id" : "el_2",
            "symbol" : "He",
            "period" : 1,
            "group" : 18, 
            "mass_upper_iupac" : 4.003,
            "mass_lower_iupac" : 4.003,
            "elemental_state" : "Gas",
            "category1" : "Non-metal",
            "category2" : "Noble gas",
            "category3" : "S-Block",
            "category4" : "Main group",
            "electronegativity" : 0,
            "ionization_energy" : 0,
            "electron_affinity" : 0,
            "common_charges" : [
                {
                    "charge" : 0
                }
            ],
            "isotope_abundance" : [
                {
                    "mass_number" : 3,
                    "abundance" : 0.00000134 
                },
                {
                    "mass_number" : 4,
                    "abundance" : 0.99999866 
                }
            ]        
    },
    {
            "element_name" : "Hydrogen" ,
            "atomic_number" : 1,
            "id" : "el_1",
            "symbol" : "H",
            "period" : 1,
            "group" : 1, 
            "mass_upper_iupac" : 1.008,
            "mass_lower_iupac" : 1.007,
            "elemental_state" : "Gas",
            "category1" : "Non-metal",
            "category2" : "Alkali metal",
            "category3" : "S-Block",
            "category4" : "Main group",
            "electronegativity" : 2,
            "ionization_energy" : 2.18e-18,
            "electron_affinity" : 72.8,
            "common_charges" : [
                {
                    "charge" : 1
                },
                {
                    "charge" : -1
                }
            ],
            "isotope_abundance" : [
                {
                    "mass_number" : 1,
                    "abundance" : 0.999885 
                },
                {
                    "mass_number" : 2,
                    "abundance" : 0.000115 
                }
            ]        
    }
]

这是HTML,如果它有帮助......

<html>
    <head>
        <title>Periodic Table Test</title>

    </head>
    <body>
        <div id="periodic_table_1"></div>
        <script src="periodic_table.js"></script>
        <div id="json_status"></div>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

你应该查看回调,它们在这样的情况下非常有用。这是针对您的示例的修复程序,但是您应该更多地查看它们,它们确实可以帮助您成长为JavaScript开发人员。

 var Parent_Object  = function() {
     parent = this;
     this.element_data;

     this.initElementData = function() {
        var request = new XMLHttpRequest();
        request.open('GET', '<data_location>', true);

        request.onload = function() {
            if (request.status >= 200 && request.status < 400) {
                parent.element_data = JSON.parse(request.responseText);  // trying to store the result as a parent class object (or whatever it would be called)...
                document.getElementById("json_status").innerHTML = "Status: JSON data successfully loaded...";
                document.getElementById("json_status").innerHTML += parent.element_data[0].element_name;  // this works fine, no problem with this!
            } else {
                document.getElementById("json_status").innerHTML = "Status: Couldn't find the JSON data...<br>";
            }

        };

        request.onerror = function() {
            document.getElementById("json_status").innerHTML = "Connection error of some sort...<br>";
        };

        request.send();
    };

    this.getElementData = function (callback) {
        if (parent.element_data !== undefined) {
            callback(parent.element_data);
        } else {
            var refreshElementsInterval = setInterval(function () {
                if (parent.element_data !== undefined) {
                    callback(parent.element_data)
                    clearInterval(refreshElementsInterval);
                }

            }, 1000);
        }
    }

    this.laterFunction = function() {
        // this is assuming you've already populated the element_data variable in the object. If you haven't it'll keep refreshing, and update your Id when you do.
        parent.getElementData(function (data) {
            document.getElementById('json_status').innerHTML = data[0].element_name;
        });
    };

}

P.S。我将Parent_Object函数的第一行更改为parent = this;而不是this.parent = this;,因为我认为这就是你的意思。