醇醛酸酯 的博客

心之所愿,无所不成

axaj异步查询学习(多级联动、校对信息)

要使用异步查询就要用到axaj,也可以说ajax有异步查询的功能,所谓的异步查询可以理解为在不整个页面刷新的情况下(即局部刷新)向服务器或者后台发送请求并拿到服务器的响应。

1. 导入jar包
要使用ajax就要先导入一些jar包,一般有json-lib-2.1-jdk15.jar,ezmorph-1.0.3.jar, commons-logging-1.1.1.jar,commons-lang-2.5.jar,commons-collections-3.1.jar, commons-beanutils-1.7.0.jar,jquery-1.10.2.min.js,jar包的版本不一定要与本文一模一样。
2.JSP页面上的操作
请求有post请求和get请求两种,本文用post请求,

<script type="text/javascript">
    var xhr=false;
    function isUsernameValid(){
    //1.创建XMLHttpRequest对象
        //非IE浏览器
        if(window.XMLHttpRequest){

            xhr=new XMLHttpRequest();

        }else if(window.ActiveXObject){//IE浏览器
            xhr=new ActiveXObject("Microsoft.XMLHTTP");
        }
        if(xhr){

            /*
                GET请求
            */
            /* //2.定义url连接
            var username = document.getElementById("username").value;
            var url = "isValidServlet";

            //3.打开服务器的连接
            xhr.open("get", url, true);

            //4.绑定回调函数(即响应回来后,可以调用的函数),readystate 0~4
            xhr.onreadystatechange = callback;

            //5.发送请求
            var username=document.getElementById("username").value;//根据id找数据
            xhr.send("username="+username); */
        /*
        post请求
        */
        //2.定义url连接

        var url="IsValidServlet";

        //3.打开服务器的连接
        xhr.open("post",url,true);
        //---------------------------post请求必须设置的参数--------------------------
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

        //4.绑定回调函数(即响应回来后,可以调用的函数),readystate 0~4
        xhr.onreadystatechange=callback;

        //5.发送请求
        var username=document.getElementById("username").value;//根据id找数据
        xhr.send("username="+username);


        }else{
            alert("XMLHttpRequest创建失败");

        }
    }

    //回调函数
    function callback(){

        if(xhr.readyState==4){//响应完成

            if(xhr.status==200){//正常响应完成 200 OK   404路径找不到  500服务器异常

                var response=xhr.responseText;
                document.getElementById("usernamemessage").innerHTML=response;
            }

        }


    }
    </script>

    <form action="RegistrationServlet" method="post">
    用户名:<input type="text" id="username" name="username" onblur="isUsernameValid()">
        <font color="red" size="-1" id="usernamemessage"></font>
    密码 :<input name="password" type="password"  id="password" />
         <input type="reset" value="重置"> 
     <input type="submit" value="登陆"> 
    </form>

上面的代码也可以这样写

<script type="text/javascript">
    var xhr = false;
    function isUsernameValid()
    {
        var username=document.getElementById("username").value;//根据id找数据
        $.ajax({
               type: "POST",
               url: "IsValidServlet",
               data: "username="+username,
               //多个参数时,比如有username,password,应该这样写:data:{"username" :username,"password" :password},
               success: function(Msg){
                document.getElementById("usernamemessage").innerHTML=Msg.message;

               }
            });
            }
            <form action="RegistrationServlet" method="post">
    用户名:<input type="text" id="username" name="username" onblur="isUsernameValid()">
        <font color="red" size="-1" id="usernamemessage"></font>
    密码 :<input name="password" type="password"  id="password" />
         <input type="reset" value="重置"> 
     <input type="submit" value="登陆"> 
    </form>

3.Servlet的操作

@WebServlet("/IsValidServlet")
public class IsValidServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    PrintWriter printWriter=null;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String username = request.getParameter("username");


        //指定HTTP响应的字符集编码
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //伪校验(不连接数据库)
        PrintWriter writer = response.getWriter();
        if("tomcat".equals(username))
        {
            String message="用户名合法";
            writer.write(message);
            /*也可以用json,代码如下
            String message="{\"message\":\"用户名合法\"}";

            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(message);
            writer.flush();
            writer.close();

            */
        }
        else
        {
            String message="用户名不合法";
            writer.write(message);
        }
        writer.flush();
        writer.close();
}

多级联动
1.jsp页面操作

    <script type="text/javascript">
    var xhr = false;
    function getSclassify()
    {
        var bclassifyObj = document.getElementById("bclassify");//拿到大分类的对象
        var bclassifyId = bclassifyObj.options[bclassifyObj.selectedIndex].value;//再拿大分类的value
        $.ajax({
               type: "POST",
               url: "getSclassifyServlet",
               data: "bclassify="+bclassify,
               success: function(sclassifies){

                //将sclassifyObj中的sid、sname绑定到city下拉列表
                var sclassifyObj = document.getElementById("sclassify");

                //清空下拉列表
                sclassifyObj.options.length = 1;
                for(var i=0;i<sclassifies.length;i++)
                {
                    var sclassify = sclassifies[i];

                    var sid = sclassify.id;
                    var sname = sclassify.sname;

                    //在下拉列表末尾添加新option
                    sclassifyObj.options[sclassifyObj.options.length] =  new Option(sname,sid);

                    }
               }
        });
    }

    <form action="">
        用户名:<input type="text" name="username"><br/><br/>
        大分类:<select id="bclassify" name="bclassify"  onchange="getSclassify()">
                <option value="">--请选择--</option>
                <option value="1000">个人护理</option>
                <option value="2000">家居用品</option>
                <option value="3000">食品饮料</option>
            </select>
        小分类:<select id="sclassify" name="sclassify"   >
            <option   >--请选择--</option>
            </select>
    </form>

2.servlet的操作

@WebServlet("/getSclassifyServlet")
public class GetSclassifyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    /**
     * 响应JSON格式文档
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String bclassifyId = request.getParameter("bclassifyId");


        //根据大分类ID查询小分类中所有符合条件的数据(应该连接数据库找,这里就写死了不去连接数据库了)
        List<Sclassify> sclassifyList = new ArrayList<Sclassify>();//Sclassify实体类里有id和name
        if("1000".equals(bclassifyId))
        {
            sclassifyList.add(new Sclassify(1001,"洗发水"));
            sclassifyList.add(new Sclassify(1002,"沐浴露"));
            sclassifyList.add(new Sclassify(1003,"牙膏"));
        }
        else if("2000".equals(bclassifyId))
        {
            sclassifyList.add(new Sclassify(2001,"厨房用品"));
            sclassifyList.add(new Sclassify(2002,"床上用品"));
            sclassifyList.add(new Sclassify(2003,"清洁用品"));
        }
        else if("3000".equals(bclassifyId))
        {
            sclassifyList.add(new Sclassify(3001,"水果"));
            sclassifyList.add(new Sclassify(3002,"酒类"));
            sclassifyList.add(new Sclassify(3003,"零食"));
        }
        JSONArray jsonArray = JSONArray.fromObject(sclassifyList);

        System.out.println("json格式响应内容:" + jsonArray.toString());

        //指定http响应字符集编码
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //响应
        PrintWriter writer = response.getWriter();
        writer.write(jsonArray.toString());
        writer.flush();
        writer.close();
    }

一般情况下,大家都喜欢用json。
4.附
如果一个jsp页面要做多个异步查询的话,需要改动几点
1.jsp页面

比如有两个需要异步查询的地方

    $.ajax({
               type: "POST",
               //url: "getSclassifyServlet",
               url: "getSclassifyServlet/getsclassify " //url地址带上后缀getsclassify
               data: "bclassify="+bclassify,
               success: function(sclassifies){
                }
                });

    $.ajax({
               type: "POST",
               //url: "getSclassifyServlet",
               url: "getSclassifyServlet/getname " //url地址带上后缀getname
               data: "bclassify="+bclassify,
               success: function(sclassifies){
                }
                });      

2.servlet页面
1.使用service方法(此方法会接收所有POST和GET请求),不用dopost和doget方法

@WebServlet("/getSclassifyServlet/*")//代表接收所有发到getSclassifyServlet的post和get请求
public class GetSclassifyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    PrintWriter printWriter=null;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String url=request.getRequestURI();//获取URL的值
    if(url.endsWith("getsclassify")){//如果URL以getsclassify结尾就调用getSclassify()方法
        getSclassify(request, response);
    }else if(url.endsWith("getname")){
        getName(request, response);
    }

protected void getSclassify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String bclassifyId = request.getParameter("bclassifyId");


        //根据大分类ID查询小分类中所有符合条件的数据(应该连接数据库找,这里就写死了不去连接数据库了)
        List<Sclassify> sclassifyList = new ArrayList<Sclassify>();//Sclassify实体类里有id和name
        if("1000".equals(bclassifyId))
        {
            sclassifyList.add(new Sclassify(1001,"洗发水"));
            sclassifyList.add(new Sclassify(1002,"沐浴露"));
            sclassifyList.add(new Sclassify(1003,"牙膏"));
        }
        else if("2000".equals(bclassifyId))
        {
            sclassifyList.add(new Sclassify(2001,"厨房用品"));
            sclassifyList.add(new Sclassify(2002,"床上用品"));
            sclassifyList.add(new Sclassify(2003,"清洁用品"));
        }
        else if("3000".equals(bclassifyId))
        {
            sclassifyList.add(new Sclassify(3001,"水果"));
            sclassifyList.add(new Sclassify(3002,"酒类"));
            sclassifyList.add(new Sclassify(3003,"零食"));
        }
        JSONArray jsonArray = JSONArray.fromObject(sclassifyList);

        System.out.println("json格式响应内容:" + jsonArray.toString());

        //指定http响应字符集编码
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //响应
        PrintWriter writer = response.getWriter();
        writer.write(jsonArray.toString());
        writer.flush();
        writer.close();
    }
    protected void getName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    /*
    这里像getSclassify()一样,写需要做的验证
    */
    }
}

希望本文可以带给你一些帮助。

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30938705/article/details/77334924
文章标签: jar ajax 异步 java jsp
个人分类: java-web java javaee
想对作者说点什么? 我来说一句

jQuery ajax 多级联动 下拉框 Demo

2015年08月06日 310KB 下载

没有更多推荐了,返回首页

不良信息举报

axaj异步查询学习(多级联动、校对信息)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭