나의보물들/jQuery

[jQuery] ajax으로 아이디 중복 체크하기

솔솔하네 2022. 2. 26. 23:09

회원가입 폼 만들면서 아이디 중복체크하기 기능 만들려고 여기저기 페이지 다쫒아 다녔지만 3일 동안

답을 못찾다 만든 나만의  ajax으로 아이디 중복 체크하기!!

 

 

 

 

🔍 만드는방법


1.'join.jsp' 파일에 아래와 같이 코드작성하면 ↑와 같이 구성 됩니다.

	  <div class="form-group">
	    <label for="exampleInputEmail1">아이디</label>
	    <input class="form-control" id="id" name="u_id" placeholder="한글 외 5자리 이상 아이디을 입력하세요">
	    <button type="button" id="idChk">중복확인</button>
	    <p id="notice"></p>
	  </div>

2. 자바스크립트에 아래와 같이 코드 써줍니다.

  - 입력받은 값을 <u_id>변수에 저장 후 ajax url로 같이 보내줍니다.

/*아이디 중복검사*/  
    $(function() {
    	$("#idChk").click(function() {
    		
    		let u_id = $("#id").val();
    		
    		$.ajax({
    			url : "idcheck.do?u_id="+u_id,
                type : 'GET',
                dataType : 'html',
                success : function(data) {
                	if (data == "1") {
//                		alert("사용가능한 아이디입니다.")
                		$("#notice").text("사용가능한 아이디입니다.")
                		$("#notice").css("color","blue")
                		$('#pw').focus();

                	} else {
//                		alert("아이디가 존재합니다.다른 아이디를 입력해주세요");
                		$("#notice").text("아이디가 존재합니다.다른 아이디를 입력해주세요.")
                		$("#notice").css("color","red")
                		$('#id').empty();
                	}
                }
    		})
    	})
    });

3. 컨트롤러에 아래와 같이 작성합니다.

  - sql검색 후 받아낸 <객체(중복아이디有)> or <Null(중복아이디無)> 중 <Null>이면 <변수uu>에 숫자 1 저장 

	// 제이쿼리로 아디디 중복확인	
	@RequestMapping(value = "idcheck.do", method = RequestMethod.GET, produces = "application/text; charset=utf-8")
	public @ResponseBody String idcheckDo(User u,HttpServletRequest req) {
		
		System.out.println(req.getParameter("u_id"));
		String uu = "";
		if(uDAO.idcheck(u,req) == null) {
			uu = "1";
		}

		return uu;
	}

4. DAO에서 아래와 같이 코드작성합니다.

 - MyBatis에서 검색 후 객체로 반환 받기

	public User idcheck(User u, HttpServletRequest req) {
		System.out.println("userDAO" + req.getParameter("u_id"));
		u.setU_id(req.getParameter("u_id"));
		User user = (User)ss.getMapper(UserMapper.class).idcheck(u);
		System.out.println(user);

			return user;
	}

5. Mapper 작성하기

<select id="idcheck" resultType="com.sol.squid.user.User">
	select * from user_info
	where u_id = #{u_id}
</select>

 

6. 고럼 요렇게 검색이 됩니다.