AJAX & JSON

AJAX:

1. Concept: ASynchronous JavaScript And XML   Asynchronous JavaScript and the XML 
1. asynchronous and synchronous: mutual communication with the client and server end * client must wait for a response server. While waiting for the client can not do other operations. * The client does not need to wait for the server's response. In the process of the server processing the request, the client may perform other operations. Ajax is a without having to reload the entire web page technical section of the page can be updated. By exchanging small amounts of data with the server behind the scenes, Ajax can make asynchronous page updates. This means that, for certain parts of the page to be updated without reloading the entire page. Traditional web page (do not use Ajax) If you need to update the content, you must reload the entire web page. Enhance the user experience of 2 ways: 1. native JS implementation (understand)










    // 1. Create a core object 
    var XMLHTTP;
     IF (window.XMLHttpRequest) 
    { // code for IE7 +, Firefox, the Chrome, Opera, Safari 
        XMLHTTP = new new the XMLHttpRequest (); 
    } 
    the else 
    { // code for IE6, IE5 
        XMLHTTP = new new the ActiveXObject ( "Microsoft.XMLHTTP" ); 
    } 

    // 2. establish connection 
    / * 
        parameters: 
            1. request mode: the GET, the POST 
                * GET mode, behind URL request parameter splicing. send an empty reference method 
                * post embodiment, the request parameters are defined in the process send 
            URL 2. request: 
            3. synchronous or asynchronous request: to true (asynchronous) or false (synchronous)
     * / 
    Xmlhttp.open ( "the GET", "? Username = ajaxServlet Tom", to true ); 

    // 3. transmission request 
    xmlhttp.send (); 

    // 4. accepting and processing a response result from the server 
    @ acquisition mode: xmlhttp.responseText 
    // when to get? When the server response after the successful acquisition 

    // When ready xmlhttp object changes, trigger events onreadystatechange. 
    = xmlhttp.onreadystatechange function () 
    { 
        // determines whether readyState ready state is 4, the response status code is determined whether the status 200 is 
        IF (4 && xmlHttp.readyState == == 200 is xmlhttp.status ) 
        { 
           // a response result of the server acquired 
            var the responseText = xmlhttp.responseText;  
            Alert (the responseText);
        } 
    }
2. JQeury implementations 1. $ .ajax () * Syntax: $ ajax ({} key-value pair);. An asynchronous request is // used $ .ajax ()



        $.ajax({
            url:"ajaxServlet1111" , // 请求路径
            type:"POST" , //请求方式
            //data: "username=jack&age=23",//请求参数
            data:{"username":"jack","age":23},
            success:function (data) {
                alert(data);
            },//响应成功后的回调函数
            error:function () {
                alert("出错啦...")
            },//表示如果请求响应出现错误,会执行的回调函数

            dataType:"text"//设置接受到的响应数据的格式
        });
  2. $.get():发送get请求
* 语法:$.get(url, [data], [callback], [type]);
* 参数:
* url:请求路径
* data:请求参数
* callback:回调函数
* type:响应结果的类型

3. $.post():发送post请求
* 语法:$.post(url, [data], [callback], [type]);
* 参数:
* url:请求路径
* data:请求参数
* callback:回调函数
* type:响应结果的类型

JSON:

1. 概念: JavaScript Object Notation       JavaScript对象表示法
Person p = new Person();
p.setName("张三");
p.setAge(23);
p.setGender("男");

var p = {"name":"张三","age":23,"gender":"男"};

* json现在多用于存储和交换文本信息的语法
* 进行数据的传输
* JSON 比 XML 更小、更快,更易解析。

2. 语法:
1. 基本规则
* 数据在名称/值对中:json数据是由键值对构成的
* 键用引号(单双都行)引起来,也可以不使用引号
* 值的 取值类型
1. 数字(整数或浮点数)
2. 字符串(在双引号中)
3. 逻辑值(true 或 false)
4. 数组(在方括号中 {"persons":[{},{}]}
5. 对象(在花括号中) {"address":{"province":"陕西"....}}
6. null
* 数据由逗号分隔:多个键值对由逗号分隔
* 花括号保存对象:使用{}定义json 格式
* 方括号保存数组:[]

2. 获取数据:
1. json对象.键名
2. json对象["键名"]
3. 数组对象[索引]
4. 遍历
        //1.定义基本格式
            var person = {"name": "张三", age: 23, 'gender': true};

            var ps = [{"name": "张三", "age": 23, "gender": true},
                {"name": "李四", "age": 24, "gender": true},
                {"name": "王五", "age": 25, "gender": false}];    
        ​
            //获取person对象中所有的键和值
            //for in 循环
           /* for(var key in person){
                //这样的方式获取不行。因为相当于  person."name"
                //alert(key + ":" + person.key);
                alert(key+":"+person[key]);
            }*/

           //获取ps中的所有值
            for (var i = 0; i < ps.length; i++) {
                var p = ps[i];
                for(var key in p){
                    alert(ke y+":"+p[key]);
                }
            }

 

3. JSON数据和Java对象的相互转换

* JSON解析器:
* 常见的解析器:Jsonlib,Gson,fastjson,jackson

1. JSON转为Java对象
1. 导入jackson的相关jar包
2. 创建Jackson核心对象 ObjectMapper
3. 调用ObjectMapper的相关方法进行转换
1. readValue(json字符串数据,Class)
2. Java对象转换JSON
1. 使用步骤:
1. 导入jackson的相关jar包
2. 创建Jackson核心对象 ObjectMapper
3. 调用ObjectMapper的相关方法进行转换
1. 转换方法:
* writeValue(参数1,obj):
                  参数1:
                      File:将obj对象转换为JSON字符串,并保存到指定的文件中
                      Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
                      OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
              * writeValueAsString(obj):将对象转为json字符串

2. 注解:
1. @JsonIgnore:排除属性。
2. @JsonFormat:属性值得格式化
* @JsonFormat(pattern = "yyyy-MM-dd")

3. 复杂java对象转换
1. List:数组
2. Map:对象格式一致
4、注意事项
   当服务器响应的数据,在客户端使用时,要想当做json数据格式使用。有两种解决方案:
1. $.get(type):将最后一个参数type指定为"json"
2. 在服务器端设置MIME类型
response.setContentType("application/json;charset=utf-8");

 

 

 

Guess you like

Origin www.cnblogs.com/timetellu/p/11615814.html