淺析ajax請求json數據並用js解析(示例分析)


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnget").click(function () {
                $.ajax({
                    type: "post",        //type:(string)請求方式,POST或GET        
                    dataType: "json",    //dataType:(string)預期返回的數據類型。xml,html,json,text等
                    url: "data.ashx",  //url:(string)發送請求的地址,可以是服務器頁面也可以是WebService動作。
                    success: function (msg) {
                        var str = "";
                        for (i in msg) {
                            str += "<tr><td>" + msg[i].id + "</td><td>" + msg[i].name + "</td><td>"
                            + msg[i].cla + "</td><td>" + msg[i].sex + "</td><td>" + msg[i].tel + "</td></tr>";
                        }
                        $("tbody").append(str);
                    }
                });
            });
        });

    </script>
</head>
<body>
    <table>
        <thead>
            <tr>
                <td>學號</td>
                <td>姓名</td>
                <td>班別</td>
                <td>性別</td>
                <td>電話</td>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <input id="btnget" type="button" value="加載數據" />
</body>
</html>

為了使表格好看一些,我們定義一下它的樣式

<style type="text/css">
    table {
        border-collapse: collapse;
    }
    table td {
        text-align: center;
        border: 1px solid gray;
        padding: 3px 10px;
    }
</style>

 

然后寫服務器端返回json數據的代碼

string data = "[{\"id\":\"2010324268\",\"name\":\"林宇\",\"cla\":\"10軟件\",\"sex\":\"男\",\"tel\":\"13800138000\"},{\"id\":\"2010324256\",\"name\":\"李四\",\"cla\":\"10網絡\",\"sex\":\"女\",\"tel\":\"10010\"},{\"id\":\"2010324264\",\"name\":\"張三\",\"cla\":\"10軟件\",\"sex\":\"男\",\"tel\":\"10086\"}]";
context.Response.Write(data);

 


免責聲明!

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



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