JQuery方式执行ajax请求

两种请求:

在这里插入图片描述

执行get请求的格式:

$.get(url,function(data,status){
这里面一般用来处理服务器反馈的数据data,将data响应到页面上
})

字节请求,不带任何参数 :

$.get("url");

需要带上参数的话与平常的get请求参数传递一样。

$.get("url?name=zhangsan&age=18");

执行post请求的格式:

$.post(url,data,function(data,status){
这里面一般用来处理服务器反馈的数据data,将data响应到页面上
},“json”) 注意:执行post请求时一定要带上数据格式"json"这是与get 的区别

直接,请求不带上任何数据:

$.post("url" );

请求,带上数据(以json的格式):

$.post("url" , {name:"xx" , age:99});

其中:
如果想要获取服务器反馈的数据,需要在get里面在加一个参数。 给定一个方法即可。服务器响应后,会执行该方法。
注意,方法里面的参数格式固定, data , status 。
data : 代表服务器响应过来的数据(多半是json和XML格式),
status 代表这次请求的响应状态码(一般不需要这个参数)。

两个例子:

一.模仿百度搜索提示

建立数据库:
在这里插入图片描述
编写前端页

<body>
<center>
    <h2>百度</h2>
    <input type="text" id="word" style="width: 600px ; height: 50px  ;font-size: 20px;">
    <input type="button" value="百度一下"  style="height: 55px ; width: 100px ; ">

    <div id="div01" style="position:relative; left : -54px; width: 600px; height: 200px ; border:  1px solid blue; display: none"></div>
</center>


</body>

编写servlet(url路径):

public class FindWordServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //获取前端传过来的word
            String word = request.getParameter("word");
            WordDaoImpl dao = new WordDaoImpl();
            //得到模糊查询出来的list集合
            List<Word> words = dao.findWord(word);

            //存放到request域中
            request.setAttribute("list",words);
            //在list.jsp中接受这个list集合
            request.getRequestDispatcher("list.jsp").forward(request,response);

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

编写支撑servlet处理数据的dao和daoImpl,返回一个wordBean的集合

public class WordDaoImpl implements WordDao {
    @Override
    public List<Word> findWord(String word) throws SQLException {
        QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from word where word like ?";

        return runner.query(sql,new BeanListHandler<Word>(Word.class),word+"%");
    }
}

用于接收集合的list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    <table style="width: 100%">
        <c:forEach items="${list}" var="wordBean">
            <tr>
                <td>${wordBean.word}</td>
            </tr>
        </c:forEach>


    </table>

最重要的jquery代码:

<script>
    $(function () {

        //触发一个键盘谈起事件
        $("#word").keyup(function () {
            //如果没有输入,则隐藏div框
            if($("#word").val() == ""){
                $("div").hide();
            }else{
                //如果有输入,则执行ajax的post请求
                $.post("FindWordServlet",{word:$("#word").val()},function (data) {
                    // alert(data) data里面是一个html的table
                    $("div").show().html(data)
                })
            }
        })
    })

</script>

二.省市联动

建立数据库
在这里插入图片描述
前端页面:

<body>
省份: <select name="province" id ="province">
    <option value="" >-请选择 -
    <option value="1" >广东
    <option value="2" >湖北
</select>
城市:
<select name="city" id="city">
    <option value="" >-请选择 -
</select>
</body>
</html>

servlet获取前端传过来的pid去dao层处理数据:
其中涉及到两个技术:
1.将集合对象转化为XML对象的格式传给前端(使用到xStream封装好的的依赖包,用xStream.toXML()方法)
2.将集合对象转化为json对象的格式传给前端(使用json封装好的依赖包,用JSONArray.fromObject(list).toString()方法)

public class CityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //1获取前端传过来的pid,转化为bean中的int类型
            int pid = Integer.parseInt(request.getParameter("pid"));
            CityDaoImpl cityDao = new CityDaoImpl();
            //2.去dao数据处理层从数据库获取想要的city集合
            List<CityBean> list = cityDao.findCityByPid(pid);

            /*//利用xstream讲list对象转化为xml的字符串
            XStream xStream = new XStream();
            //想把pid做成属性
            xStream.useAttributeFor(CityBean.class, "pid");
            //设置别名
            xStream.alias("city", CityBean.class);
            String xml = xStream.toXML(list);*/

            //3.将list对象转化为json对象数组
            JSONArray jsonArray = JSONArray.fromObject(list);
            String json = jsonArray.toString();
//            System.out.println(json);

            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(json);//响应给前端页面的数据

        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

dao处理数据:

public class CityDaoImpl implements CityDao {

    @Override
    public List<CityBean> findCityByPid(int pid) throws SQLException {

        QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from city where pid=?";
        return runner.query(sql,new BeanListHandler<CityBean>(CityBean.class),pid);
    }
}

前端jq-ajax获取到servlet响应回来的json对象(也就是回调函数里的参数data):

        $(function () {
            //select一旦发生改变,就通过value值(也就是pid)去servlet中找到该省份对应的城市集合
            $("#province").change(function () {
                //清空select下的子元素option
                $("#city").empty()

                //发送一个post请求,把value的值(也就是pid)带到servlet中,servlet响应回来一个data(xml,json)
                $.post("CityServlet",{pid:$(this).val()},function (data) {

                    /*//处理xml类型的数据
                    $(data).find("city").each(function () {
                        var id = $(this).children("id").text();
                        var cname = $(this).children("cname").text();
                        $("#city").append("<option value='"+id+"'>"+cname);
                    })*/
                    
                    //处理json类型的数据
                    $(data).each(function (i,n) {
                        // alert(n.cname)
                        $("#city").append("<option value='"+i+"'>"+n.cname);
                    })

                },"json")
            })
        })

服务器响应回来的两种数据格式:

1.json

 [
            {
                "cname":"深圳",
                "id":1,
                "pid":1
            },
            {
                "cname":"广州",
                "id":2,
                "pid":1
            },
                {"cname":"惠州",
                "id":3,
                "pid":1
            },
                {"cname":"东莞",
                "id":4,
                "pid":1
            }
         ]

2.xml格式:

<list>
	         <city pid="1">
	                <id>1</id>
	                <cname>深圳</cname>
	          </city>
	          <city pid="1">
	                <id>2</id>
	                <cname>广州</cname>
	          </city>
	          <city pid="1">
	                <id>3</id>
	                <cname>惠州</cname>
	          </city>
	          <city pid="1">
	                <id>4</id>
	                <cname>东莞</cname>
	          </city>
</list>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值