ajax 实现局部页面更新

导入

导入

 

 

 

<script src="views/js/jquery-2.1.0.js"></script>
  <script>
    //name:username
    username.onblur = function () {                       //多个数据传递使用英文逗号隔开
      $.post("/yuer/ajaxIsLogin",{username:username.value,age:19},function (data) {
        //第一个参数:响应的servlet地址,第二个参数:传递servlet过去的参数,第三个参数:接受回传的参数
        if(data.code == "110"){
          $("#usernameMessage").html("此用户名已被使用").css("color","red");
        }else{
          $("#usernameMessage").html("您可以使用此用户名").css("color","green");
        }
      });
    }
  </script>

servlet页面

package com.person.servlet;

import com.alibaba.fastjson.JSON;
import com.person.dao.IUserDAO;
import com.person.dao.impl.UserDAOImpl;

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;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ajaxIsLogin")
public class IsLoginServlet extends HttpServlet {
    /**
     * ajax传递局部刷新
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        IUserDAO userDAO = new UserDAOImpl();
        boolean exits = userDAO.ajaxIsLogin(username);
        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter out=resp.getWriter();
        Map<Object,Object> map = new HashMap<>();
        if (exits){
            map.put("code","110");
            map.put("message","error");
        }else {
            map.put("code","120");
        }
        String s = JSON.toJSONString(map);
        out.write(s);
        out.close();
    }
}

 

posted @ 2019-07-01 20:32  织式  阅读(2002)  评论(0编辑  收藏  举报