Json(一)

Json技术

  1. Json简介
    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。
    它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。

JSON:JavaScript 对象表示法(JavaScript Object Notation) 。
JSON 是存储和交换文本信息的语法。类似 XML。
JSON 比 XML 更小、更快,更易解析。

2.JSON格式语法

        JSON 对象
        { "name":"张三" , "age":22}

        JSON 数组
        {
            "student": [
                { "name":"张三" , "age":22 },
                { "name":"李四" , "age":23 },
                { "name":"王五" , "age":24 }
            ]
        }

        JSON 嵌套
        {
            "student": [
                { "name":"张三" , "age":22 ,"score":{"chinese":90,"math":100,"english":80} },
                { "name":"李四" , "age":23 ,"score":{"chinese":70,"math":90, "english":90} },
                { "name":"王五" , "age":24 ,"score":{"chinese":80,"math":60, "english":90} }
            ]
        } 

        把Json串换成 Json对象
        var dataObj=eval("("+data+")");//转换为 json 对象

3.Json 第三方 jar 包
Json-lib
简单的例子来体验

    <div>
    <input type="button" onclick="loadInfo()" value="Ajax获取信息"/>&nbsp;&nbsp;
    姓名:<input type="text" id="name" name="name" />&nbsp;&nbsp;
    年龄:<input type="text" id="age" name="age" />
    </div>

然后调用相应的js去解决

function loadInfo(){
        var xmlHttp;
        if(window.XMLHttpRequest){
            xmlHttp=new XMLHttpRequest();
        }else{
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
                alert(xmlHttp.responseText);//返回的是一个串,然后再解析成json对象
                var dataObj=eval("("+xmlHttp.responseText+")");//变成一个对象
                alert(dataObj.name);
                alert(dataObj.age);
                document.getElementById("name").value=dataObj.name;
                document.getElementById("age").value=dataObj.age;
            }
        };
        xmlHttp.open("get", "getAjaxInfo?action=jsonObject", true);//在用get的方式  getAjaxInfo是请求的servlet true异步

        xmlHttp.send();
    }

相应的处理的servlet是

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String action=request.getParameter("action");
        if("jsonObject".equals(action)){
            this.getJsonObject(request, response);
        }else if("jsonArray".equals(action)){
            this.getJsonArray(request, response);
        }else if("jsonNested".equals(action)){
            this.getJsonNested(request, response);
        }

    }


    private void getJsonObject(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        // String resultJson="{\"name\":\"张三\",\"age\":22}";
        JSONObject resultJson=new JSONObject();
        resultJson.put("name", "张三");
        resultJson.put("age", 22);
        out.println(resultJson);
        out.flush();
        out.close();
    }

如果传递过来的是一个数组对象,那么其中应该包括:

<div style="margin-top: 20px;">
        <input type="button" onclick="loadInfo2()" value="Ajax获取信息2"><br/>
        <table id="studentTable" align="center" border="1px;" cellpadding="0px;">
            <tr>
                <th>姓名</th><th>年龄</th><th>得分</th>
            </tr>
        </table>
    </div>
function loadInfo2(){
        var xmlHttp;
        if(window.XMLHttpRequest){
            xmlHttp=new XMLHttpRequest();
        }else{
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
                alert(xmlHttp.responseText);
                var dataObj=eval("("+xmlHttp.responseText+")");
                var st=document.getElementById("studentTable");
                alert(dataObj.students.length);
                var newTr; // 行
                var newTd0; // 第一列
                var newTd1; // 第二列
                var newTd2; // 第三列
                for(var i=0;i<dataObj.students.length;i++){
                    var student=dataObj.students[i];
                    newTr=st.insertRow();
                    newTd0=newTr.insertCell();
                    newTd1=newTr.insertCell();
                    newTd2=newTr.insertCell();
                    newTd0.innerHTML=student.name;
                    newTd1.innerHTML=student.age;
                    newTd2.innerHTML="语文:"+student.score.chinese+",数学:"+student.score.math+",英语:"+student.score.english;
                }
            }
        };
        // xmlHttp.open("get", "getAjaxInfo?action=jsonArray", true);
        xmlHttp.open("get", "getAjaxInfo?action=jsonNested", true);
        xmlHttp.send();
    }

最后处理的servlet

    private void getJsonArray(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        JSONObject resultJson=new JSONObject();//最后返回的json结果对象

        JSONArray jsonArray=new JSONArray();//用来接收数组对象      
        JSONObject jsonObject1=new JSONObject();//对象1
        jsonObject1.put("name", "张三");
        jsonObject1.put("age", 22);
        JSONObject jsonObject2=new JSONObject();//对象2
        jsonObject2.put("name", "李四");
        jsonObject2.put("age", 23);
        JSONObject jsonObject3=new JSONObject();//对象3
        jsonObject3.put("name", "王五");
        jsonObject3.put("age", 24);

        jsonArray.add(jsonObject1);
        jsonArray.add(jsonObject2);
        jsonArray.add(jsonObject3);

        resultJson.put("students", jsonArray);
        out.println(resultJson);
        out.flush();
        out.close();
    }

如果要是存在像第三种结构的那种嵌套的json结构

private void getJsonNested(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        JSONObject resultJson=new JSONObject();//最后的结果对象

        JSONArray jsonArray=new JSONArray();//用来存放学生的数组

        JSONObject jsonObject1=new JSONObject();//对象1
        jsonObject1.put("name", "张三");
        jsonObject1.put("age", 22);     
        JSONObject scoreObject1=new JSONObject();//其中的分数对象
        scoreObject1.put("chinese", 90);
        scoreObject1.put("math", 100);
        scoreObject1.put("english", 80);
        jsonObject1.put("score", scoreObject1);

        JSONObject jsonObject2=new JSONObject();//对象2
        jsonObject2.put("name", "李四");
        jsonObject2.put("age", 23);     
        JSONObject scoreObject2=new JSONObject();//其中的分数对象
        scoreObject2.put("chinese", 70);
        scoreObject2.put("math", 90);
        scoreObject2.put("english", 90);
        jsonObject2.put("score", scoreObject2);

        JSONObject jsonObject3=new JSONObject();//对象3
        jsonObject3.put("name", "王五");
        jsonObject3.put("age", 24);     
        JSONObject scoreObject3=new JSONObject();//其中的分数对象
        scoreObject3.put("chinese", 80);
        scoreObject3.put("math", 60);
        scoreObject3.put("english", 90);
        jsonObject3.put("score", scoreObject3);

        jsonArray.add(jsonObject1);
        jsonArray.add(jsonObject2);
        jsonArray.add(jsonObject3);

        resultJson.put("students", jsonArray);
        out.println(resultJson);
        out.flush();
        out.close();
    }

处理的过程可以参照上面的步骤。

4.Ajax&Json 交互简单实例
1)Ajax来验证用户名
用户注册界面

<body>
<table>
    <tr>
        <th>用户注册</th>
    </tr>
    <tr>
        <td>用户名:</td>
        <td><input type="text" id="userName" name="userName" onblur="checkUserName()"/>&nbsp;&nbsp;<font id="tip"></font></td>
    </tr>
    <tr>
        <td>密码:</td>
        <td><input type="text" id="password" name="password"/></td>
    </tr>
    <tr>
        <td>确认密码:</td>
        <td><input type="text" id="password2" name="password2"/></td>
    </tr>
    <tr>
        <td><input type="submit" value="注册"/></td>
        <td><input type="button" value="重置"/></td>
    </tr>
</table>
</body>

检查处理

<script type="text/javascript">
    function checkUserName(){
        var userName=document.getElementById("userName").value;
        var xmlHttp;
        if(window.XMLHttpRequest){
            xmlHttp=new XMLHttpRequest();
        }else{
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
                alert(xmlHttp.responseText);
                var dataObj=eval("("+xmlHttp.responseText+")");
                if(dataObj.exist){
                    document.getElementById("tip").innerHTML="<img src='no.png'/>&nbsp;该用户名已经存在";
                }else{
                    document.getElementById("tip").innerHTML="<img src='ok.png'/>&nbsp;该用户名可用";
                }
            }
        };
        xmlHttp.open("get", "getAjaxInfo?action=checkUserName&userName="+userName, true);

        xmlHttp.send();
    }
</script>
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String action=request.getParameter("action");
        if("checkUserName".equals(action)){
            this.checkUserName(request, response);
        }else if("ejld".equals(action)){
            this.ejld(request, response);
        }

    }
private void checkUserName(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String userName=request.getParameter("userName");
        JSONObject resultJson=new JSONObject();
        if("jack".equals(userName)){
            resultJson.put("exist", true);
        }else{
            resultJson.put("exist", false);
        }
        out.println(resultJson);
        out.flush();
        out.close();
    }

2)城市的二级联动
界面设计

<body>
省:
<select id="sheng" onchange="loadInfo()">
    <option value="1">江苏省</option>
    <option value="2">山东省</option>
    <option value="3">浙江省</option>
</select>
&nbsp;&nbsp;
市
<select id="shi">
</select>
</body>

事件处理

<script type="text/javascript">
    function loadInfo(){
        var shengId=document.getElementById("sheng").value;
        shi.options.length=0;  // 删除所有市下拉框的选项
        var xmlHttp;
        if(window.XMLHttpRequest){
            xmlHttp=new XMLHttpRequest();
        }else{
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
                alert(xmlHttp.responseText);
                var dataObj=eval("("+xmlHttp.responseText+")");
                for(var i=0;i<dataObj.rows.length;i++){
                    var o=dataObj.rows[i];
                    shi.options.add(new Option(o.text,o.id));
                }
            }
        };
        xmlHttp.open("get", "getAjaxInfo?action=ejld&shengId="+shengId, true);

        xmlHttp.send();
    }
</script>

中间过程

    private void ejld(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String shengId=request.getParameter("shengId");
        JSONObject resultJson=new JSONObject();
        JSONArray jsonArray=new JSONArray();
        JSONObject temp=null;
        switch(Integer.parseInt(shengId)){
            case 1:{
                temp=new JSONObject();temp.put("id", 1);temp.put("text", "南京");jsonArray.add(temp);
                temp=new JSONObject();temp.put("id", 2);temp.put("text", "南通");jsonArray.add(temp);
                temp=new JSONObject();temp.put("id", 3);temp.put("text", "泰兴");jsonArray.add(temp);
                break;
            }
            case 2:{
                temp=new JSONObject();temp.put("id", 4);temp.put("text", "济南");jsonArray.add(temp);
                temp=new JSONObject();temp.put("id", 5);temp.put("text", "烟台");jsonArray.add(temp);
                temp=new JSONObject();temp.put("id", 6);temp.put("text", "蓬莱");jsonArray.add(temp);
                break;
            }
            case 3:{
                temp=new JSONObject();temp.put("id", 7);temp.put("text", "杭州");jsonArray.add(temp);
                temp=new JSONObject();temp.put("id", 8);temp.put("text", "宁波");jsonArray.add(temp);
                temp=new JSONObject();temp.put("id", 9);temp.put("text", "温州");jsonArray.add(temp);
                break;
            }
        }
        resultJson.put("rows", jsonArray);
        out.println(resultJson);
        out.flush();
        out.close();
    }

以上基本上就是Json和Ajax的一个综合运用。
资料获取:
https://github.com/hlfsunshine/AjaxLearning

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值