JavaScript使用JSON格式模擬從后端傳輸數據到前端


學習JSON時為了能夠更直觀的看到JSON的作用
於是使用JavaScript模擬了使用JSON格式從后端傳輸數據到前端的案例


什么是JSON?

JSON: JavaScript Object Notation(JavaScript 對象表示法)

JSON 是存儲和交換文本信息的語法,類似 XML

JSON 比 XML 更小、更快,更易解析

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>JSON是一種輕量級的數據交換格式</title>
    <script type="text/javascript">
        /* JavaScript模擬從后端使用JSON格式傳輸數據到前端的案例 */
        window.onload = function () {
            var employee = {
                    "total": 3,
                    "information": [{
                        "name": "sam",
                        "sex": "man",
                        "salary": 1000
                    }, {
                        "name": "lisa",
                        "sex": "woman",
                        "salary": 2000
                    }, {
                        "name": "heber",
                        "sex": "man",
                        "salary": 3000
                    }]
                }
            // 獲取到"employee"JSON對象中total鍵(key)
            var total = employee.total;
            // 獲取到"employee"JSON對象中"information"數組
            var Info = employee.information;
            // 獲取到"展示員工信息"按鈕對象
            var showInfo = document.getElementById("showInformation");
            // 獲取到表格"tbody"標簽
            var body = document.getElementById("body");
            // 獲取到"span"標簽
            var count = document.getElementById("count");
            // 定義一個接收員工信息的空字符串
            var elements = "";
            // 點擊按鈕顯示員工信息的函數
            var flag = true;
            showInfo.onclick = function () {
                // 循環遍歷JSON數組中的值並使用"+="拼接起來
                // 如果不拼接則會僅顯示循環完畢后最后一組數組的值
                for (var i = 0; i < Info.length; i++) {
                    elements += "<tr>" + "<td>" + Info[i].name + "</td>" +
                        "<td>" + Info[i].sex + "</td>" + "<td>" + Info[i].salary + "</td>" + "</tr>";
                }
                // 將拼接好的值傳入"tbody"標簽中
                body.innerHTML = elements;
                // 將拼接好的值傳入"span"標簽中
                count.innerHTML = total;
                // 為了避免多次點擊生成多余數據,將按鈕設置為只觸發一次后失效
                showInfo.onclick = null;
            }
        }
    </script>
</head>

<body style="text-align: center;">
    <input type="button" value="顯示員工信息" id="showInformation" />
    <hr />
    <table border="1px" width="300px" height="50px" align="center">
        <thead>
            <tr>
                <th colspan="3">員工信息表</th>
            </tr>
            <tr>
                <th>姓名</th>
                <th>性別</th>
                <th>工資</th>
            </tr>
        </thead>
        <tbody id="body" align="center">
        </tbody>
    </table>
</body>
共有<span id="count">0</span> 條數據
</html>
代碼運行效果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM