LoginSignup
1
2

More than 5 years have passed since last update.

JSONデータの取得と値の持ち回り

Last updated at Posted at 2017-12-02

前提・実現したいこと

我ながらお恥ずかしい話ですが、APIから取得するデータでツリー表示をさせ、画面上にデータとして残すようなページをサンプルで作っています。
どうか皆様のアドバイス(ソースコード)などのお力添えをお願いいたします。
環境等は最下部に記載しています。
以下が実現したいことです。

Jsonデータ ⇒ 取得してツリー表示(初期表示) ⇒ ツリー内のボタン(プラスボタンなど) ⇒対象のJsonデータを再度取得 ⇒ 取得したデータを画面上の任意の箇所に表示ボタンが押された場合にのみ表示

イメージ

-書店
  - BOOK
       ワンピース☑️
+ホテル
+電気
+八百屋


                 表示ボタン


表示場所[ワンピース]

チェック箇所の情報をHTML(thymeleaf)内の任意の場所に表示する。
表示内容はイメージのとこにあるワンピースという名称でページ数などは裏で結びついて持っていきたい。

発生している問題・エラーメッセージ

AjaxとJavaでの連携でJsonを取得して、ツリー表示できない。
実現できるなら、AjaxでもJavaでもどちらでもいいのですが、Jsonをツリー表示するのがわからなく、プラスボタンで再度Jsonデータを呼びに行く方法がわからないという現状です。

該当のソースコード

@Service
public class ZipCodeService {

    @Autowired
    @Qualifier("zipCodeSearchRestTemplate")
    RestTemplate restTemplate;

    /** サンプル検索API リクエストURL */
    private static final String URL = "http://zipcloud.ibsnet.co.jp/api/search?zipcode={zipcode}";

    public ZipCodeDto service(String zipcode) {
        return restTemplate.getForObject(URL, ZipCodeDto.class, zipcode);
    }

}
@Controller
public class ZipCodeController {

    @Autowired
    ZipCodeService zpcService;

    /**
     * サンプル入力フォーム
     * @return "zipcode"
     */
    @RequestMapping("/zipcode")
    public String zipcodeForm(HttpSession session, Model model) {
        return "zipcode";
    }

    /**
     * サンプル情報表示 
     * @return "zipcode-confirm"
     */
    @RequestMapping(value="/zipcode/confirm", method=RequestMethod.POST)
    public String zipcodeConfirm(HttpSession session, Model model, 
                                 @RequestParam("zipcode") String zipcode){

        // 一応必須チェックのみ 数字・桁数チェックは省略
        // nullまたは空文字の場合、入力フォームにエラーメッセージを表示
        if (zipcode == null || zipcode.equals("")) {
            model.addAttribute("errorMessage", "郵便番号を入力してください。");
            return zipcodeForm(session, model);
        }

        // サンプル検索APIサービス呼び出し
        ZipCodeDto zipCodeDto = zpcService.service(zipcode);
        // thymeleafでリストを展開して表示する
        model.addAttribute("zipcodeList", zipCodeDto.getResults());
        return "zipcode-confirm";   
    }
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="imagetoolbar" content="no" />
        <title>設置サンプル</title>
        <link rel="stylesheet" type="text/css" href="/content/lib/yui/build/treeview/treeview.css?_yuiversion=2.4.1" />
        <link rel="stylesheet" type="text/css" href="/content/lib/yui/build/treeview/tree.css?_yuiversion=2.4.1" />
        <script type="text/javascript" src="/content/lib/yui/build/yahoo/yahoo.js?_yuiversion=2.4.1"></script>
        <script type="text/javascript" src="/content/lib/yui/build/event/event.js?_yuiversion=2.4.1"></script>
        <script type="text/javascript" src="/content/lib/yui/build/treeview/treeview.js?_yuiversion=2.4.1"></script>
        <style type="text/css">
            * {
                margin:0; padding:0;
            }
            body{
                margin:0 auto; padding:0;
                background-color:#666;
                color:#666;
                font:81%/1.5 verdana,sans-serif;
                text-align:center;
            }
            #wrap {
                width:500px;
                margin:0 auto; padding:0;
                background-color:#fff;
                text-align:center;
            }
            #content {
                margin:0 20px; padding:0;
                text-align:left;
            }
            #footer {
                margin:1em 0 0 0; padding:.2em .5em;
                background-color:#999;
                color:#fff;
                font-size:78%;
                text-align:right;
            }
            #footer * {
                font-style:normal;
                font-size:100%;
                color:#fff;
            }
            h1 {
                margin:0 0 1em 0; padding:.5em 1em;
                background-color:#999;
                color:#fff;
                font-size:100%;
                text-align:left;
            }
            h1 a {
                color:#fff;
            }
            p {
                margin:1em 0; padding:0;
            }
            img {
                border:0;
            }
        </style>
    </head>
    <body>
        <div id="wrap">
            <h1>設置サンプル</h1>
            <p>参照:<a href="http://developer.yahoo.com/yui/examples/treeview/folder_style.html">YUI Library &raquo; Tree View Control &raquo; Folder-Style TreeView Design</a></p>
            <div id="content">
                <p>
                    <a id="expand" href="#">Expand all</a> | 
                    <a id="collapse" href="#">Collapse all</a>
                </p>
                <div id="treeDiv1"></div>
                <script type="text/javascript">
                //an anonymous function wraps our code to keep our variables
                //in function scope rather than in the global namespace:
                (function() {
                    var tree; //will hold our TreeView instance
                    function treeInit() {
                        YAHOO.log("Example's treeInit function firing.", "info", "example");
                        //Hand off ot a method that randomly generates tree nodes:
                        buildRandomTextNodeTree();
                        //handler for expanding all nodes
                        YAHOO.util.Event.on("expand", "click", function(e) {
                            YAHOO.log("Expanding all TreeView  nodes.", "info", "example");
                            tree.expandAll();
                            YAHOO.util.Event.preventDefault(e);
                        });
                        //handler for collapsing all nodes
                        YAHOO.util.Event.on("collapse", "click", function(e) {
                            YAHOO.log("Collapsing all TreeView  nodes.", "info", "example");
                            tree.collapseAll();
                            YAHOO.util.Event.preventDefault(e);
                        });
                    }
                    //This method will build a TreeView instance and populate it with
                    //between 3 and 7 top-level nodes
                    function buildRandomTextNodeTree() {
                        //instantiate the tree:
                        tree = new YAHOO.widget.TreeView("treeDiv1");

                        //create top-level nodes
                        for (var i = 0; i < Math.floor((Math.random()*4) + 3); i++) {
                            var tmpNode = new YAHOO.widget.TextNode("label-" + i, tree.getRoot(), false);

                            //we'll delegate to another function to build child nodes:
                            buildRandomTextBranch(tmpNode);
                        }
                        //once it's all built out, we need to render
                        //our TreeView instance:
                        tree.draw();
                    }
                    //This function adds a random number <4 of child nodes to a given
                    //node, stopping at a specific node depth:
                    function buildRandomTextBranch(node) {
                        if (node.depth < 6) {
                            YAHOO.log("buildRandomTextBranch: " + node.index);
                            for ( var i = 0; i < Math.floor(Math.random() * 4) ; i++ ) {
                                var tmpNode = new YAHOO.widget.TextNode(node.label + "-" + i, node, false);
                                buildRandomTextBranch(tmpNode);
                            }
                        }
                    }
                    //When the DOM is done loading, we can initialize our TreeView
                    //instance:
                    YAHOO.util.Event.onDOMReady(treeInit);
                })();//anonymous function wrapper closed; () notation executes function
                </script>
            </div><!-- div#wrap/div#content -->
        </div><!-- div#wrap -->
    </body>
</html>

jQuery( function() {
    jQuery( '#jquery-sample-button' ) . toggle(
        function() {
            jQuery . ajax( {
                url: 'jquery-sample-ajax-json.php',
                dataType: 'json',
                data: {
                    year: '2011',
                    month: '11',
                    day: '25'
                },
                success: function( data ) {
                    jQuery . each( data, function( key, value ) {
                        jQuery( '#jquery-sample-ajax' ) . append( '<p>' + key + ': ' + value + '</p>' );
                    } );
                    jQuery( '#jquery-sample-textStatus' ) . text( '読み込み成功' );
                },
                error: function( data ) {
                    jQuery( '#jquery-sample-textStatus' ) . text( '読み込み失敗' );
                }
            } );
        },
        function() {
            jQuery( '#jquery-sample-ajax' ) . html( '' );
            jQuery( '#jquery-sample-textStatus' ) . text( '' );
        }
    );
} );

対象のJSONデータ

{
 "book1":{
"title": "Book",
 "year": 2005 ,
"page": 399
},
"book2":{
 "title": "ワンピース",
 "year": 2006 ,
"page": 650
 }
}

補足情報(言語/FW/ツール等のバージョンなど)

STS、SpringBoot、Java8,Javascript、HTML、Timeleaf

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2