使用ajax验证数据库的名字是否重复(只展示ajax+servlet的代码)

script的关键代码:

<script>
    //使用ajax验证数据库的名字是否重复
    $(function () {
			
        $('#Id').blur(function () {

            var Id = document.getElementById("Id");

            if (Id.value != "") {

                if (window.XMLHttpRequest) {
                    xml = new XMLHttpRequest();
                } else {
                    xml = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xml.onreadystatechange = function () {
                    if (xml.readyState == 4 && xml.status == 200) {
                        document.getElementById("AjaxInfo").innerHTML = xml.responseText;
                        //alert("ajax输出成功!");
                    }
                };
                xml.open("POST", "InsertServlet?Id=" + Id.value, true);
                xml.send();
            } else if (Id.value == "") {
                document.getElementById("AjaxInfo").innerHTML = "内容不能为空";
            }
        })

    })
</script>

以下是servlet的关键代码:

			request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");

            String Id=request.getParameter("Id");
            Id = new String(productId.getBytes("iso-8859-1"),"gb2312");

            ProductService productService=new ProductServiceImpl();
			ProductInfo productInfo=new ProductInfo();
            try {
                productInfo=productService.find(productId);

                if (productInfo==null){

                    response.getWriter().println("代码可用");

                }else{
                    response.getWriter().println("代码不可用");
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("验证产生异常了");
            }
发布了108 篇原创文章 · 获赞 46 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_44739706/article/details/104587105