Ajax的复习(二):用json对象

Ajax的复习(二):用json对象

笔记总结自:Ajax入门到精通全套完整版(ajax2020最新版本)Web前端Ajax初学者零基础学习必备

  • json格式理解简单,含义清晰
  • json格式数据在多种语言中比较容易处理。使用java、js等读写json格式的数据比较容易
  • json格式数据占用的空间小,在网络中传输的速度快,用户的体验好

json分类

  • json对象

    JSONObject,这种对象的格式是 名称:值 (所谓的“名称-值对”),也可以看作是 key : value 格式

    {名称 : 值} 或者说 { key : value }
    
  • json数组

    JSONArray,基本格式 [ { name:“河北” , jiancheng:“冀”,"shenghui:“石家庄” } , {name:“山西” , jiancheng:“晋”,"shenghui:“太原”} ]

     [ { name:"河北" , jiancheng:"冀","shenghui:"石家庄" } , {name:"山西" , jiancheng:"","shenghui:"太原"} ]
    

json实现项目

  1. myjajx页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>使用json格式的数据</title>
    <script type="text/javascript">
        function doSearch() {
            //1. 创建异步对象
            let xmlHttpRequest = new XMLHttpRequest();
            //2. 绑定事件
            xmlHttpRequest.onreadystatechange = function () {
                //处理返回的数据
                if(xmlHttpRequest.readyState === 4&&xmlHttpRequest.status ===200){
                    var data = xmlHttpRequest.responseText;
                    alert(data);
                    console.log(data);
                    //执行括号中的代码,把json字符串转为json对象
                    var jsonobj = eval("("+data+")");

                    callback(jsonobj);
                }
            }

            let proid = document.getElementById("proid").value;
            //3. 初始化请求
            xmlHttpRequest.open("get","queryjson?proid="+proid,true);

            //4.发送请求
            xmlHttpRequest.send();
        }

        function callback(jsonobj) {
            document.getElementById("proname").value = jsonobj.name;
            document.getElementById("proeasyname").value = jsonobj.esayName;
            document.getElementById("procenter").value = jsonobj.captical;
        }
    </script>
</head>
<body>
<h1 align="center">Ajax请求使用json格式的数据</h1>
<hr>
<table align="center">
    <tr>
        <td>省份编号:</td>
        <td>
        <input type="text" id="proid" >
        <input type="button" value="搜索" οnclick="doSearch()">
        </td>
    </tr>
    <tr>
        <td>省份名称:</td>
        <td>
        <input type="text" id="proname" >
        </td>
    </tr>
    <tr>
        <td>省份简称:</td>
        <td>
        <input type="text" id="proeasyname" >
        </td>
    </tr>
    <tr>
        <td>省会:</td>
        <td>
        <input type="text" id="procenter" >
        </td>
    </tr>
</table>
</body>
</html>
  1. Privince实体类
package com.liang.entity;

/**
 * 省份的实体类
 * @author liang
 * @date 编写日期: 2022/3/11 22:16
 */
public class Province {


    private Integer id;
    private String name;
    private String esayName;
    private String captical;

    /**
     * 无参构造方法
     */
    public Province() {
    }

    /**
     * 全参构造
     * @param id id
     * @param name 名称
     * @param esayName 简称
     * @param captical 省会
     */
    public Province(Integer id, String name, String esayName, String captical) {
        this.id = id;
        this.name = name;
        this.esayName = esayName;
        this.captical = captical;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEsayName() {
        return esayName;
    }

    public void setEsayName(String esayName) {
        this.esayName = esayName;
    }

    public String getCaptical() {
        return captical;
    }

    public void setCaptical(String captical) {
        this.captical = captical;
    }

}
  1. 获取省份对象方法
    /**
     * 获取省份
     * @param proviceid
     * @return
     */
    public static Province queryProvince(Integer proviceid){
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        Province p = null;
        try {
            //1. 获取连接
            con = ProvinceDao.getConnection();
            //2. 获取数据库操作对象
            String sql = "select id,name,jiancheng,shenghui from pro where id = ?";
            ps = con.prepareStatement(sql);
            ps.setInt(1,proviceid);
            res = ps.executeQuery();
            if(res.next()){
                p = new Province();
                p.setId(res.getInt("id"));
                p.setName(res.getString("name"));
                p.setEsayName(res.getString("jiancheng"));
                p.setCaptical(res.getString("shenghui"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ProvinceDao.release(con,ps,res);
        }
        return p;
    }
  1. Servlet
package com.liang.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liang.entity.Province;
import com.liang.service.QueryInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author liang
 * @date 编写日期: 2022/3/11 23:28
 */
@WebServlet("/queryjson")
public class QueryJsonProvince extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //获取请求参数,省份的id
        String strProid = req.getParameter("proid");
        //默认值
        String json = "{}";
        //判断是有值
        if(strProid != null&&strProid.trim().length() > 0){
            Province p = QueryInfo.queryProvince(Integer.valueOf(strProid));
            //需要使用jackson把对象转为json
            ObjectMapper om = new ObjectMapper();
            json = om.writeValueAsString(p);
        }

        //把获取到的对象,通过网络传给异步对象
        //指定返回的格式是json
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.write(json);
        out.flush();
        out.close();


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req, resp);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值