• 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>

     

    该花的钱要花,该吃的饭要吃。
  • 相关阅读:
    洛谷 P2700 逐个击破
    洛谷 P1503 鬼子进村
    洛谷 P1556 幸福的路
    洛谷 P1490 买蛋糕
    洛谷 P2507 [SCOI2008]配对
    code vs 3305 水果姐逛水果街Ⅱ
    通过idea远程调试
    【Cocos2d-x JavaScript Binding】
    ☀【SeaJS】SeaJS Grunt构建
    -_-#【Better Code】throttle / debounce
  • 原文地址:https://www.cnblogs.com/chao666/p/12026409.html
Copyright © 2020-2023  润新知