jQuery中Ajax的get、post等方法详解

2020-05-23 06:01:09易采站长站整理

    <script src=”../../js/jquery-2.1.3.js”></script>
    <style>
        * { margin:0; padding:0;}
        body { font-size:12px;}
        .comment { margin-top:10px; padding:10px; border:1px solid #ccc;background:#DDD;}
        .comment h6 { font-weight:700; font-size:14px;}
        .para { margin-top:5px; text-indent:2em;background:#DDD;}
    </style>
    <title></title>
</head>
<body>
<br/>
<p>
    <input type=”button” id=”send” value=”加载”/>
</p>
<div  class=”comment”>已有评论:</div>
<div id=”resText” >
</div>
</body>
<script type=”text/javascript”>
    $(function () {
        $(‘#send’).click(function() {
            $.getJSON(‘test.json’, function(data) {
                $(‘#resText’).empty();
                var html = ”;
                $.each( data  , function(commentIndex, comment) {
                    html += ‘<div class=”comment”><h6>’ + comment[‘username’] + ‘:</h6><p class=”para”>’ + comment[‘content’] + ‘</p></div>’;
                })
                $(‘#resText’).html(html);
            })
        })
    })
</script>
</html>

test.json文件为:


[
  {
    “username”: “张三”,
    “content”: “沙发.”
  },
  {
    “username”: “李四”,
    “content”: “板凳.”
  },
  {
    “username”: “王五”,
    “content”: “地板.”