ajax应用

ajax应用

一、异步校验用户名是否存在

1.需求:

ajax应用_第1张图片
用户名是否存在.png

2.代码:

JQ代码:


HTML代码:


服务端代码:

public class CheckUsernameServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //获得要校验的用户名
        String username = request.getParameter("username");
        
        //传递username到service
        UserService service = new UserService();
        boolean isExist = false;
        try {
            isExist = service.checkUsername(username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        response.getWriter().write("{\"isExist\":"+isExist+"}");
        
    }

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

二、站内搜索

JS代码:



HTML代码:


服务端代码:

public class SearchWordServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //获得关键字
        String word = request.getParameter("word");
        
        //查询该关键字的所有商品
        ProductService service = new ProductService();
        List productList = null;
        try {
            productList = service.findProductByWord(word);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        //["xiaomi","huawei",""...]
        
        //使用json的转换工具将对象或集合转成json格式的字符串
        /*JSONArray fromObject = JSONArray.fromObject(productList);
        String string = fromObject.toString();
        System.out.println(string);*/
        
        Gson gson = new Gson();
        String json = gson.toJson(productList);
        System.out.println(json);
        
        response.setContentType("text/html;charset=UTF-8");
        
        response.getWriter().write(json);
        
        
    }

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

    } 

                            
                        
                    
                    
                    

你可能感兴趣的:(ajax应用)