jQuery调用ajax获取json格式数据

时间:2021-02-25 19:38:38
<body>
<div>点击按钮获取音乐列表</div>
<input type="button" id="button" value="确定" />
<div id="result"></div>
<div>添加新的音乐</div>
<input type="text" name="" id="" value="" />
<input type="button" id="button2" value="添加" />
</body>
<script type="text/javascript">

    $(document).ready(function(){

        $('#button').click(function(){

            $.ajax({ 

                type:"GET", 

                url:"json/music.txt", //路径

                dataType:"json", 

                success:function(data){ 

                var music="<h2>"; 

                //i表示在data中的索引位置,n表示包含的信息的对象 

                $.each(data,function(i,n){ 

                    //获取对象中属性为optionsValue的值 

                    music+="<div>"+n["optionValue"]+"</div>"; 

                }); 

                music+="</h2>"; 

                    $('#result').append(music); 

                } 

            }); 

            return false; 

        }); 

    }); 

</script>
[
{"optionKey":"1", "optionValue":"Need you now"},
{"optionKey":"2", "optionValue":"According to you"},
{"optionKey":"3", "optionValue":"Thriller"},
{"optionKey":"4", "optionValue":"dreadful"}
]