簡體   English   中英

在html中使用JSON文件

[英]Using JSON files in html

我很難理解如何使用保存在JSON文件中的數據並將其加載到html頁面中。

    { 

    "level1":{
        "level1_1":{
            "example": "test",
            "example2":"123123"
        },
        "level1_2":{
            "example": "test",
            "example2":"123123"
        }
    },

    "level2":{
        "level2_1":{
            "example": "test",
            "example2":"123123"
        },
        "level2_2":{
            "example": "test",
            "example2":"123123"
        }
    }

}

我希望能夠從中調用數據,例如在HTML文件中:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>reading json</title>
  <style>

  </style>

</head>
<body>

  <br>
  file value :

  <br>

<script>
function loadJSON(callback) {   

var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
xobj.open('GET', 'config.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
      if (xobj.readyState == 4 && xobj.status == "200") {
        // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
        callback(xobj.responseText);
      }
};
xobj.send(null);  
}

function init() {
 loadJSON(function(response) {
  // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
 });
}
</script>

</body>

我從本教程中獲得了腳本, 仍然可以運行它。 所以我的目的只是為了查看JSON文件中的** first value **數據。 你知道你們是怎么做到的嗎?

這是一個更詳盡的答案。

首先,讓我們將JSON解析為一個對象。

var actual_JSON = JSON.parse(response);

其次,將JSON對象轉換為可讀的字符串。

var json_string = JSON.stringify(actual_JSON, undefined, 2);

然后,使用querySelector()函數選擇一個DOM元素。 請注意, #output表示我想選擇一個名為outputID屬性。

var output = document.querySelector("#output");

然后,我使用JSON innerHTML屬性將JSON字符串添加到DOM中。 它將在“文件值”之后添加。

output.innerHTML += json_string;
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>reading json</title>
  <style>

  </style>

</head>
<body>

  <br>
  <div id="output">file value : </div>
  <br>

<script>

// Starts.
init();

function loadJSON(callback) {   
  var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");
  xobj.open('GET', 'config.json', true); // Replace 'my_data' with the path to your file
  xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
          callback(xobj.responseText);
          // init(xobj.responseText)
        }
  };
  xobj.send(null);  
}

function init() {
  loadJSON(function(response) {

    // Parse JSON string into object
    var actual_JSON = JSON.parse(response);

    // Transforms the JSON object into a readable string.
    var json_string = JSON.stringify(actual_JSON, undefined, 2);

    // Select <br> tag.
    var output = document.querySelector("#output");

    // Adds it to the DOM.
    output.innerHTML += json_string;
  });
}

</script>
</body>

您必須在html中添加一些id屬性,然后根據該id選擇並循環json數據並像這樣插入

<!doctype html>

    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>reading json</title>
      <style>

      </style>

    </head>
    <body>

    <div id="json_result"></div>
<script>
function loadJSON(callback) {   

var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
xobj.open('GET', 'config.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
      if (xobj.readyState == 4 && xobj.status == "200") {
        // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
        callback(xobj.responseText);
      }
};
xobj.send(null);  
}

function init() {

 loadJSON(function(response) {
  // Parse JSON string into object
    var actual_JSON = JSON.parse(response); 

    for (var key in actual_JSON) {
        var innerkey = actual_JSON[key];
        for (var inner in innerkey) {
             document.getElementById('json_result').innerHTML += 'Example: '+innerkey[inner]['example']+'<br>';
             document.getElementById('json_result').innerHTML += 'Example2: '+innerkey[inner]['example2']+'<br>';
        }   
    }   
 }); 
}
init();
</script>

</body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM