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


<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src=""></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" value="加载"/>
</p>
<div >已有评论:</div>
<div >
</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><h6>' + comment['username'] + ':</h6><p>' + comment['content'] + '</p></div>';
                })
                $('#resText').html(html);
            })
        })
    })
</script>
</html>

test.json文件为:

复制代码 代码如下:


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


 
使用JSONP形式的回调函数来加载其他网站的JSON数据。例如:

复制代码 代码如下:


<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src=""></script>
    <style>
        * { margin:0; padding:0;}
        body { font-size:12px;}
        .para {
            width:100px;
            height:100px;
            margin:5px;
            border:0;
        }
    </style>
    <title></title>
</head>
<body>
<p>
    <input type="button" value="加载"/>
</p>
<div >
</div>
</body>
<script type="text/javascript">
    $(function () {
        $('#send').click(function() {
            $.getJSON("=?",
                    function(data){
                        $.each(data.items, function( i,item ){
                            $("<img/> ").attr("src", item.media.m).appendTo("#resText");
                            if ( i == 3 ) {
                                return false;
                            }
                        });
                    }
            );
        })
    })
    /**
     *  JSONP(JSON with Padding)是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过JavaScript Callback的形式实现跨域访问
     *  上述的url地址并不能请求到数据,仅用作说明。
     * */
</script>
</html>

注意:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxysp.html