Ajax之追加到表格

追加到表格.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
    <title>Document</title>
    </head>
    <body>
        <table width="500" border="1">
            <tr>
                <th>姓名
               <th>年齡
               <th>性別
           </tr>
        </table>
    <button>點擊
    <script src="ajax3.0-min.js">
    <script>
    // 需求:當點擊button按鈕的時候,獲取服務器的數據,並追擊到table表格中
    // 1.獲取table表格
        var table = document.getElementsByTagName('table')[0];
        var btn = document.getElementsByTagName('button')[0];
    // 2.點擊事件
        btn.onclick = function() {
        // ajax獲取數據:是一個對象,需要在Ajax()函數傳遞"JSON"的參數,約束了msg是對象類型的數據
        Ajax('JSON').get('2.json', function(msg) {
            console.log(msg);
            // console.log(typeof msg);
            var str = '';
            for (var i = 0; i < msg.length; i++) {
                str += '';
                str += '' + msg[i]['username'] + '';
                str += '' + msg[i]['age'] + '';
                str += '' + msg[i]['sex'] + '';
                str += '';
            }
            // 將拼裝的字符串寫入到table中
            table.innerHTML += str;
        })
    }
    </script>
</body>
</html>

2.json

[
    { "username": "張三", "age": 30, "sex": "\u7537" },
    { "username": "\u7545\u7545", "age": 28, "sex": "\u5973" },
    { "username": "\u5cf0\u54e5", "age": 36, "sex": "\u7537" },
    { "username": "\u5cf0\u54e5\u5ac2\u5b50", "age": 44, "sex": "\u5973" }
]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章