zoukankan      html  css  js  c++  java
  • Ajax,Json数据格式

    同步和异步

    同步现象:客户端发送请求到服务器端,当服务器返回响应之前,客户端都处于等待     卡死状态

    异步现象:客户端发送请求到服务器端,无论服务器是否返回响应,客户端都可以随     意做其他事情,不会被卡死

    Ajax的运行原理

    页面发起请求,会将请求发送给浏览器内核中的Ajax引擎,Ajax引擎会提交请求到      服务器端,在这段时间里,客户端可以任意进行任意操作,直到服务器端将数据返回      给Ajax引擎后,会触发你设置的事件,从而执行自定义的js逻辑代码完成某种页面1    功能。

    js原生的Ajax技术,异步和同步操作

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    /* 1)创建Ajax引擎对象
    2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
    3)绑定提交地址
    4)发送请求
    5)接受响应数据
     */
     function f1(){
         //1)创建Ajax引擎对象
         var xmlhttp=new XMLHttpRequest();
        //2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
         xmlhttp.onreadystatechange=function(){
             //5)接受响应数据
             if(xmlhttp.readyState==4&&xmlhttp.status==200){
                 var res=xmlhttp.responseText;
                document.getElementById("span1").innerHTML=res;
             }
         }
        //3)绑定提交地址
         xmlhttp.open("GET", "${pageContext.request.contextPath}/AjaxServlet", true);//请求方式,请求地址,是否异步
         //4)发送请求
         xmlhttp.send();
    }
     function f2(){
         //1)创建Ajax引擎对象
         var xmlhttp=new XMLHttpRequest();
        //2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
         xmlhttp.onreadystatechange=function(){
             //5)接受响应数据
             if(xmlhttp.readyState==4&&xmlhttp.status==200){
                 var res=xmlhttp.responseText;
                 alert(res);
             }
         }
        //3)绑定提交地址
         xmlhttp.open("POST", "${pageContext.request.contextPath}/AjaxServlet", true);//请求方式,请求地址,是否异步
         xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
         //4)发送请求
         xmlhttp.send("name=张三");
    }
     function f3(){
         //1)创建Ajax引擎对象
         var xmlhttp=new XMLHttpRequest();
        //2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
         xmlhttp.onreadystatechange=function(){
             //5)接受响应数据
             if(xmlhttp.readyState==4&&xmlhttp.status==200){
                 var res=xmlhttp.responseText;
                 document.getElementById("span2").innerHTML=res;
             }
         }
        //3)绑定提交地址
         xmlhttp.open("GET", "${pageContext.request.contextPath}/AjaxServlet", false);//请求方式,请求地址,是否异步
         //4)发送请求
         xmlhttp.send();
    }
    </script>
    </head>
    <body>
        <input value="异步访问" type="button" onclick="f1()">
        <span id="span1"></span>
        <br>
        <input value="同步访问" type="button" onclick="f3()">
        <span id="span2"></span>
        <br>
        <input value="测试" type="button" onclick="alert()">
    </body>
    </html>

    Ajaxservlet:

    package com.oracle.web;
    
    import java.io.IOException;
    import java.util.Random;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class AjaxServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            /*request.setCharacterEncoding("utf-8");
            String name=request.getParameter("name");
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(name+"你好");*/
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.getWriter().write(new Random().nextDouble()+"");
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    Json数据格式

    json是一种与语言无关的数据交换的格式,作用:

      使用ajax进行前后台数据交换

      移动端与服务端的数据交换

    Json格式

      1)对象格式:{"key1":obj,"key2":obj,"key3":obj...}

      2)数组/集合格式:[obj,obj,obj...]

    例如:user对象 用json数据格式表示

    {"username":"zhangsan","age":28,"password":"123","addr":"淄博"}

    List<Product> 用json数据格式表示

    [{"pid":"10","pname":"小米4C"},{},{}]

    注意:对象格式和数组格式可以互相嵌套

      json的key是字符串  jaon的value是Object

    json的解析

    json是js的原生内容,也就意味着js可以直接取出json对象中的数据

    Json的转换插件

    将java的对象或集合转成json形式字符串

    json的转换插件是通过java的一些工具,直接将java对象或集合转换成json字符串。

    常用的json转换工具有如下几种:

    1)jsonlib

    2)Gson:google

    3)fastjson:阿里巴巴

    json例子

    <script language="JavaScript">
        /**
         * 案例一
         *  {key:value,key:value}
         *  
         * class Person{
         *       String firstname = "张";
         *    String lastname = "三丰";
         *    Integer age = 100;
         * }
         * 
         * Person p = new Person();
         * System.out.println(p.firstname);
         */
        var person={"firstname":"","lastname":"三丰","age":100};
         alert(person.lastname);
         alert(person.age); 
    
      </script>
    <script language="JavaScript">
          /**
         * 案例二
         *  [{key:value,key:value},{key:value,key:value}]
         *  
         */
         var persons=[{"name":"zhangsan",age:18},{"name":"lisi",age:19},{"name":"wangwu",age:20}];
         alert(persons[1].name);
         alert(persons[2].age);
    
      </script>
    <script language="JavaScript">
       /**
         * 案例三
         * {
         *   "param":[{key:value,key:value},{key:value,key:value}]
         * }
         *  
         *  
         */
        var school= {
             "c0601班":[{"name":"张三","age":23},{"name":"李四","age":20}],
             "c0602班":[{"name":"赵四","age":34},{"name":"王强","age":25}]
         };
         
        alert(school.c0601班[1].name);
         
        
        
      </script>

    jQuery的Ajax技术

    jquery是一个优秀的js框架,自然对js原生的ajax进行了封装,封装后的ajax的操   作方法更简洁,功能更强大,与ajax操作相关的jquery方法有如下几种,但开发中 经常使用的有三种

    1)$.get(url, [data], [callback], [type])

    2)$.post(url, [data], [callback], [type])

      其中:

        url:代表请求的服务器端地址

        data:代表请求服务器端的数据(可以是key=value形式也可以是json格式)

        callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)

        type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换)

        常用的返回类型:text、json、html等

    3)$.ajax( { option1:value1,option2:value2... } ); ---- 以后在掌握

    常用的option有如下:

      async:是否异步,默认是true代表异步

      data:发送到服务器的参数,建议使用json格式

      dataType:服务器端返回的数据类型,常用text和json

      success:成功响应执行的函数,对应的类型是function类型

      type:请求方式,POST/GET

      url:请求服务器端地址

    例子:

    user实体类:

    package com.oracle.domain;
    
    public class User {
        private String name ;
        private int age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return "User [name=" + name + ", age=" + age + "]";
        }
        
    }

    jsp页面代码

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script src="${pageContext.request.contextPath }/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function f1(){
            $.get(
                    "${pageContext.request.contextPath }/Ajax2Servlet",
                    {"name":"zhangsan","age":18},
                    function(data){
                        alert(data.name);
                    },
                    "json"
            )
        }
        function f2(){
            $.post(
                    "${pageContext.request.contextPath }/Ajax2Servlet",
                    {"name":"zhangsan","age":18},
                    function(data){
                        alert(data.name);
                    },
                    "json"
            )
        }
        function f3(){
            $.ajax({
                url:"${pageContext.request.contextPath }/Ajax2Servlet",
                async:true,
                type:"POST",
                data:{"name":"lusi","age":18},
                success:function(data){
                    alert(data.name);
                },
                error:function(){
                    alert("请求失败");
                },
                dataType:"json"
                
            })
        }
    </script>
    </head>
    <body>
    <input type="button" value="get异步提交服务器" onclick="f1()">
    <input type="button" value="PSOT同步提交服务器" onclick="f2()">
    <input type="button" value="ajax提交服务器" onclick="f3()">
    </body>
    </html>

    servlet代码:

    package com.oracle.web;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    import com.oracle.domain.User;
    
    public class Ajax2Servlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");
            String agestr=request.getParameter("age");
            int age=Integer.parseInt(agestr);
            User user=new User();
            user.setAge(age);
            user.setName(name);
            Gson gs=new Gson();
            String js=gs.toJson(user);
            System.out.println(js);
        response.getWriter().write("{"name":""+name+"","age":"+age+"}");
            response.getWriter().write(js);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
  • 相关阅读:
    单元测试之block
    (转)CBCentralManager Class 的相关分析
    (转)iOS蓝牙调用的一般流程
    facebook pop 学习笔记
    GitHub 上值得关注学习的 iOS 开源项目
    关于block以及__bridge的一些笔记
    你的iOS静态库该减肥了
    iOS--消息推送后方法回调情况(简)
    UINavgation日常小bug-有兴趣的朋友可以看看
    UIDynamic(一)
  • 原文地址:https://www.cnblogs.com/lzw123-/p/9809242.html
Copyright © 2011-2022 走看看