Ajax之处理不同格式的JSON数据

JSON是一种网络中的数据格式,主要用于网络间的数据传输,它比XML格式的数据传输速度快,使用更广。

1.Ajax处理对象格式的JSON数据:

 1 <script src="../JS/jquery-1.12.4.min.js"></script>
 2     <script>
 3     function show(){
 4             // Ajax使用GET简化方式,请求JSON数据
 5             // get请求格式:get(url,传递给服务器的参数,请求成功后执行的函数,能够解析的数据格式)
 6             $.get('student.json',{},function(response){
 7                 // 当请求成功JSON解析出来的数据有两个,一个是对象/数组,还有一个所示请求状态码
 8                 // response是解析后的数据,
 9                 // 如果JSON解析之前的数据是数组,那么response就是数组
10                 // 如果JSON解析之前的数据是对象,那么response就是对象
11                 var $name = $('#name');
12                 var $age = $('#age');
13                 var $sex = $('#sex');
14                 var $school = $('#school');
15                 $name.html(response.name);
16                 $age.html(response.age);
17                 $sex.html(response.sex);
18                 $school.html(response.school);
19             },'JSON').error(function(){
20                 alert('Error!');
21             });
22             // Ajax利用POST方式进行数据传输
23             $.post('student.json',{},function(response){
24                 $('#name').html(response.name);
25                 $('#age').html(response.age);
26                 $('#sex').html(response.sex);
27                 $('#school').html(response.school);
28             },'JSON').error(function(){
29                 alert('Error!');
30             });
31 }
32     </script>

2.Ajax处理数组格式的JSON数据:

<script src="js/jquery-1.12.4.min.js"></script>
    <script>
        $(function(){
            $.get('resume.json',{},function(response){
                $('#photo').html("<img src='"+response[0]+"'>");
                $('#name').html(response[1]);
                $('#age').html(response[2]);
                $('#school').html(response[3]);
                $('#langage').html(response[4]);
                $('#empiric').html(response[5]);
                $('#habby').html(response[6]);
                $('#reward').html(response[7]);
            },'JSON').error(function(){
                $('#div').html('<h1>对不起,请求错误!</h1>')
            });
        });
    </script>

 

猜你喜欢

转载自www.cnblogs.com/chao666/p/12026409.html