【问题标题】:Display data from local json file on webpage在网页上显示来自本地 json 文件的数据
【发布时间】:2019-01-17 22:09:09
【问题描述】:

我目前正在尝试将本地 JSON 文件 (universities.json) 中的数据显示到网页上的表格中。这是我当前的代码:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>

</head>
<body>
    <div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "universities.json";

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myArr = JSON.parse(this.responseText);
        myFunction(myArr);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + 
        arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>

我在这里搜索了很多问题并进行了无数次谷歌搜索,但我不知道为什么这不起作用。这只是代码的一次迭代;我也尝试过其他各种方法。我知道我没有包含任何表格的代码,但我已经删除了它,直到我可以以任何格式提取数据。

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 能否将样本数据包含在universities.json 中?这将帮助我们复制问题
  • 您可以创建数据的模拟,然后调用myFunction。这样你就可以知道问题出在检索 json 还是函数本身。
  • 这段代码没有明显的问题,但是如果您在浏览器的开发人员中查看控制台,如果您发现有关从用户文件系统读取文件的大错误消息,我不会感到惊讶工具。
  • 另一件事,当你调试这个时,检查网络选项卡,看看你得到的 AJAX 调用的响应

标签: javascript html json


【解决方案1】:

您的浏览器安全不允许您发出此请求,并且您收到CORS 错误,为了绕过此,您有以下两个选项。

1.更改您的浏览器安全设置。 例如,在 Chrome 中,您可以通过导航到 Chrome 安装文件夹并使用以下命令运行 chrome 来执行此操作,然后尝试在浏览器中再次测试

chrome.exe --allow-file-access-from-files

2.在本地运行一个网络服务器,把你所有的文件放在同一个路径中。

【讨论】:

    【解决方案2】:

    CORS 错误是由 Mahdi 前面提到的浏览器安全引起的。

    如果您的 HTML 文件只是从浏览器中的本地驱动器打开(仅限客户端)并且未托管在本地或远程网络服务器,您应该尝试使用纯 JavaScript 中的 FileReader(),而不是使用 XMLHttpRequest()。做这样的事情:

      function fnUploadFile() {
        var objFileReader;
        var inputFile;
        var flLocalFile;
    
        if (window.File && window.FileReader && window.FileList && window.Blob) {
          // All the File APIs are supported.
        } else {
          alert('A required API is not supported on this browser. You need HTML5 browsers!');
          return; // abort execution
        }
    
        inputFile = document.getElementById('inLocallySelectedFile');
    
        if (!inputFile) {
          alert("File selector control not found!");
        } else if (!inputFile.files[0]) {
          alert("Have you selected a file yet? Select a file before clicking 'Process File'!");
        } else {
          // open and read file with JavaScript FileReader
          flLocalFile = inputFile.files[0];
          objFileReader = new FileReader();
          objFileReader.onload = function(event) {
            // event.target == FileReader
            var contents = event.target.result;
            fnConvertToJSON(contents);
          };
          objFileReader.readAsText(flLocalFile);
        }
    
        function fnConvertToJSON(results) {
          var JSONData = JSON.parse(results);
          var ctrlJSONDisplay = document.getElementById('JsonDataDisplay')
          ctrlJSONDisplay.innerHTML = "<strong><u>" + JSONData['name'] +
            "</u></strong> is <strong><u>" + JSONData['age'] +
            "</u></strong> years old and from the <strong><u>" +
            JSONData['country'] + "</u></strong>";
        }
    
      }
        <form id="frmGetLocalFile" name="frmGetLocalFile" method="post">
          <h1>Select Your File</h1>
          <input type='file' accept="*" name='inLocallySelectedFile' id='inLocallySelectedFile'>
          <input type='button' id='btProcessFile' name="btProcessFile" value='Process File' onclick='fnUploadFile();'>
        </form>
    
    
        <div>
          <p>Assuming JSON File Content:</p>
          <pre>
    { 
       "name": "John", 
       "age" : 30, 
       "country" : "UK" 
    }
    </pre>
          <hr>
          <p>JSON Data read from local file:</p>
          <p id="JsonDataDisplay"></p>
        </div>

    See code in JSFiddle: https://jsfiddle.net/TechOnTheBeach/3gsa2y75/3/

    【讨论】:

      【解决方案3】:

      无法从代码沙箱中提供文件。 但是,遵循(服务器端)代码示例可以解决问题:

      const http = require("http");
      
      http
        .createServer((req, res) => {
          if (req.method === "GET" && req.url == "/") {
            res.writeHead(200, {
              "Content-Type": "text/html"
            });
            res.end(`<!DOCTYPE html>
              <html>
                <body>
                  <div id="id01"></div>
                </body>
                <script>
                  const getJson = () => {
                    let xhr = new XMLHttpRequest();
                    xhr.open('GET', '/getjson', true);
                    xhr.onload = () => {
                      if (xhr.readyState == 4 && xhr.status == 200)
                        json = JSON.parse(xhr.responseText);
                        jsons = [];
                        Object.values(json).forEach((value,index) => {
                          jsons.push('<a href="'+value+'">"'+Object.keys(json)[index]+'"</a>');
                        });
                        jsons.forEach(item => document.querySelector('#id01').innerHTML += item+'<br>');
      
                    };
                    xhr.send();
                  };
                  getJson();
                </script>
              </html>`);
          }
          if (req.method === "GET" && req.url.match(/getjson/)) {
            let json = `{ "Univ1": "https://univ1.edu", "Univ2": "https://univ2.edu", "Univ3": "https://univ3.edu" }`;
            res.writeHead(200, {
              "Content-Type": "application/json"
            });
            res.end(json);
          }
        })
        .listen(8080);
      

      https://codesandbox.io/s/j2yj6577q3

      【讨论】:

        猜你喜欢
        • 2019-12-28
        • 2018-03-21
        • 1970-01-01
        • 1970-01-01
        • 2020-07-01
        • 2017-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多