반응형
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

bro's coding

AJAX.post 본문

[IT]/AJAX

AJAX.post

givemebro 2021. 6. 9. 10:55
반응형
package step4;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AjaxPostServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String pno = request.getParameter("pno");
		System.out.println("서버에서 pno 전달받음 " + pno);
		out.print(pno + "번 게시물을 삭제했습니다");
		out.close();
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function startAjax() {
		let postNoValue = document.getElementById("postNo").value;
		if (postNo.value == "") {
			alert("게시물번호를 입력하세요!");
			return;// 함수 실행 종료
		}

		// alert("startAjax");
		let xhr = new XMLHttpRequest();
		// readyState 상태값이 변경될때 실행될 함수(callback 함수)를 등록
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4 && xhr.status == 200) {
				alert(xhr.responseText);
				document.getElementById("deleteResult").innerHTML = xhr.responseText;
			}
		}// callback 함수 등록

		// post!!!
		xhr.open("post", "AjaxPostServlet");
		// post방식은 content-type을 지정해야한다
		xhr.setRequestHeader("Content-Type",
				"application/x-www-form-urlencoded");
		xhr.send("pno=" + postNoValue);
	}
</script>
</head>
<body>
	<input type="number" id="postNo" placeholder="게시물번호">
	<button type="button" onclick="startAjax()">삭제</button>
	<span id="deleteResult"></span>

</body>
</html>
반응형

'[IT] > AJAX' 카테고리의 다른 글

AJAX.XML/JSON  (0) 2021.06.09
Ajax  (0) 2021.06.08
JSON.INFO  (0) 2021.05.08
AJAX.예제  (0) 2021.05.06
AJAX/JSON  (0) 2021.05.06
Comments