欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery異步獲取json數(shù)據(jù)方法匯總

 更新時(shí)間:2014年12月22日 14:57:34   投稿:hebedich  
這篇文章主要介紹了jQuery異步獲取json數(shù)據(jù)方法的2種方式,并附上了示例,推薦給有需要的小伙伴。

jQuery異步獲取json數(shù)據(jù)有2種方式,一個(gè)是$.getJSON方法,一個(gè)是$.ajax方法。本篇體驗(yàn)使用這2種方式異步獲取json數(shù)據(jù),然后追加到頁(yè)面。

在根目錄下創(chuàng)建data.json文件:

復(fù)制代碼 代碼如下:

{
    "one" : "Hello",
    "two" : "World"
}

■ 通過(guò)$.getJSON方法獲取json數(shù)據(jù)

復(fù)制代碼 代碼如下:

    <script src="Scripts/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $.getJSON('data.json', function(data) {
                var items = [];
                $.each(data, function(key, val) {
                    items.push('<li id="' + key + '">' + val + '</li>');
                });
                $('<ul/>', {
                    'class': 'list',
                    html: items.join('')
                }).appendTo('body');
            });
        });
    </script>

 

■ 通過(guò)$.ajax方法獲取json數(shù)據(jù)

復(fù)制代碼 代碼如下:

    <script src="Scripts/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $.ajax({
                url: 'data.json',
                dataType: 'json',
                success: function(data) {
                    var items = [];
                    $.each(data, function(key, val) {
                        items.push('<li id="' + key + '">' + val + '</li>');
                    });
                    $('<ul/>', {
                        'class': 'list',
                        html: items.join('')
                    }).appendTo('body');
                },
                statusCode: {
                    404: function() {
                        alert("沒(méi)有找到相關(guān)文件~~");
                    }
                }
            });
        });
    </script>

總結(jié):使用$.getJSON方法和$.ajax方法都能達(dá)到相同的效果,但是,如果想對(duì)異步獲取的過(guò)程有更細(xì)節(jié)的控制,推薦使用$.ajax方法。

相關(guān)文章

最新評(píng)論