[英]Display data from local json file on webpage
I am currently trying to display data from a local JSON file (universities.json) into a table on a webpage. 我目前正在尝试将本地JSON文件(colleges.json)中的数据显示到网页上的表中。 This is my current code:
这是我目前的代码:
<!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>
I have searched through so many questions on here and done countless google searches yet I cannot find out why this will not work. 我在这里搜索了很多问题并完成了无数谷歌搜索,但我无法找到为什么这不起作用。 This is just one iteration of the code;
这只是代码的一次迭代; I have tried various other ways too.
我也尝试了其他各种方法。 I'm aware I don't have any code for a table included, but I have removed that until I can get the data pulling through in any format.
我知道我没有包含任何表格的代码,但是我已经将其删除,直到我能够以任何格式获取数据。
Any help would be much appreciated. 任何帮助将非常感激。 Thanks
谢谢
Your browser security is not allowing you to make this request, and you are getting CORS
error, in order to bypass this, you have two following options. 您的浏览器安全性不允许您发出此请求,并且您收到
CORS
错误,为了绕过此问题,您有以下两个选项。
1.Alter your browser security settings. 1.更改浏览器安全设置。 For example, in Chrome, you can do this by navigating to Chrome installation folder and Run chrome with the following command, then try to test again in the browser
例如,在Chrome中,您可以通过导航到Chrome安装文件夹并使用以下命令运行chrome来执行此操作,然后尝试在浏览器中再次测试
chrome.exe --allow-file-access-from-files
2.Run a Webserver locally and put all your file in the same path. 2.在本地运行Web服务器并将所有文件放在同一路径中。
Couldn't manage to serve files from within codesandbox. 无法管理来自codesandbox内的文件。 However, following (serverside) codesample, does the trick:
但是,在(服务器端)代码示例之后,诀窍是:
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 https://codesandbox.io/s/j2yj6577q3
The CORS error is due to browser security as Mahdi mentioned earlier. CORS错误是由于Mahdi之前提到的浏览器安全性。
If your HTML file is just opened from local drive in your browser ( client-side only ) and not hosted on a local nor remote web server , instead of using XMLHttpRequest(), you should try using FileReader() from pure JavaScript. 如果您的HTML文件只是从浏览器中的本地驱动器( 仅限客户端 ) 打开而不是托管在本地或远程Web服务器上 ,而不是使用XMLHttpRequest(),则应尝试使用纯JavaScript中的FileReader()。 Do something like this:
做这样的事情:
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/ 请参阅JSFiddle中的代码:https://jsfiddle.net/TechOnTheBeach/3gsa2y75/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.