允许用户上传 JSON,然后使用 JSON 呈现页面

Allow user to upload JSON, then use the JSON to render the page

目前在我的网站上,我允许用户将 JSON 数据粘贴到 HTML 表单中,然后我使用 JSON 数据来改变页面的呈现。如何用文件上传功能替换表单?我不需要将数据存储在 Web 服务器上。只要能在浏览器中运行就没问题。我的网站是用PHP写的。谢谢

这是一个简单的演示程序,它提示用户输入文件、读取文件并将内容发布到 <textarea>。它还将 JSON 内容解析为变量并将其发送到 console.log。从这里您应该能够解压缩数据并更新您的页面。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Reader Demo</title>
</head>
<body>
<form id="fileForm">
    <input type="file" name="fileItem" id="fileItem" required>
    <input type="submit">
</form>
<textarea id="fileContents"></textarea>
<script>
    (function(){
        "use strict";
        // Add an event handler to the form's submit event
        document.getElementById('fileForm').addEventListener('submit', function(e){
            // Stop the browser submitting anything
            e.preventDefault();
            // Get the file object
            let file = document.getElementById('fileItem').files[0];
            // Check the file is actually JSON
            if (file.type !== "application/json") {
                document.getElementById('fileContents').value = "Invalid file type"+file.type;
            } else {
                // Create a file reader
                let reader = new FileReader();
                // Add an event handler to the 'load' event
                reader.addEventListener('load', function (e) {
                    // Post the file contents to the page
                    document.getElementById('fileContents').value = e.target.result;
                    // parse the JSON
                    let jsonData = JSON.parse(e.target.result);
                    // Process incoming JSON data here.
                    console.log(jsonData);
                })
                // Read the file as text. We'll parse it with JSON.parse later
                reader.readAsText(file);
            }
        })
    })();
</script>
</body>
</html>