jQuery.ajax(url[,settings])で、JSON形式のデータを読み込みパースし表示

jQuery の jQuery . ajax( url [, settings] ) メソッドを使った Ajax リクエストで、JSON形式のデータを読み込み、パースし、表示する方法。

実装例(サンプル)

実装例(サンプル)の動作について

「toggle」ボタンをクリックすると、「jquery-sample-ajax-json.js」ファイルを読み込み、パースし、黄色のボックス要素内に表示する。

読み込みが成功すると、「toggle」ボタンの右横に「読み込み成功」と表示する。

「toggle」ボタンを、再度クリックすると、元に戻す。

実装例(サンプル)のソースコード

JavaScript

<script>
<!--
jQuery( function() {
    jQuery( '#jquery-sample-button' ) . toggle(
        function() {
            jQuery . ajax(
                'jquery-sample-ajax-json.js',
                {
                    dataType: 'json',
                    success: function( data ) {
                        var title = '<h3>' + data . title + '</h3>';
                        jQuery( '#jquery-sample-ajax' ) . append( title );
                        jQuery . each( data . color, function( index ) {
                            var name = data . color[index] . name;
                            var colorName = data . color[index] . colorName;
                            var colorCode = data . color[index] . colorCode;
                            var html = '<p style="color:' + colorName + ';">' + name + ':' + colorName + ':' + colorCode + '</p>';
                            jQuery( '#jquery-sample-ajax' ) . append( html );
                        } );
                        jQuery( '#jquery-sample-textStatus' ) . text( '読み込み成功' );
                    },
                    error: function( data ) {
                        jQuery( '#jquery-sample-textStatus' ) . text( '読み込み失敗' );
                    }
                }
            );
        },
        function() {
            jQuery( '#jquery-sample-ajax' ) . html( '' );
            jQuery( '#jquery-sample-textStatus' ) . text( '' );
        }
    );
} );
// -->
</script>

CSS

<style type="text/css">
<!--
#jquery-sample {
    margin: 10px;
    width: 300px;
}
#jquery-sample-ajax {
    margin: 10px;
    padding: 10px;
    height: 150px;
    background-color: yellow;
    border: 1px solid gray;
    border-radius: 10px;
}
-->
</style>

HTML

<div id="jquery-sample">
    <p>
        <button id="jquery-sample-button">toggle</button>
        <span id="jquery-sample-textStatus"></span>
    </p>
    <div id="jquery-sample-ajax"></div>
</div>

読み込むjsonファイルの内容

{
    "title": "サンプル",
    "color":
        [
            {
                "name": "赤色",
                "colorName": "red",
                "colorCode": "#ff0000"
            },
            {
                "name": "青色",
                "colorName": "blue",
                "colorCode": "#0000ff"
            },
            {
                "name": "緑色",
                "colorName": "green",
                "colorCode": "#008000"
            }
        ]
}

スポンサード リンク

カテゴリー: Ajax, API, JavaScript, jQuery パーマリンク