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

bro's coding

AJAX.예제 본문

[IT]/AJAX

AJAX.예제

givemebro 2021. 5. 6. 10:29
반응형
package step1;

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 AsyServlet
 */

public class AsynServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

	int count;
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// ajax응답
		out.println("hello ajax count:"+count++);
		System.out.println(getServletName()+"doGet()");
		out.close();
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax 기본 예제</title>
<script type="text/javascript">
	let xhr;
	function startAjax(){		
		xhr=new XMLHttpRequest();//Ajax 통신을 위한 자바스크립트 객체 
		//alert(xhr);
		//XMLHttpRequest의 속성에 callback 함수를 바인딩
		//readystate가 변화될 때 callback 함수가 실행 
		//서버가 응답할 때 callback 함수를 실행하기 위한 코드이다 
		xhr.onreadystatechange=callback; 
		//서버로 요청 
		xhr.open("GET","AsynServlet");
		xhr.send(null); //post 방식일때 form data 명시 
	}
	function callback(){
		//alert(xhr.readyState);
		// readyState 가 4 : 서버의 응답 정보를 받은 상태 
		// status 가 200 : 정상 수행 
		if(xhr.readyState==4&&xhr.status==200){
			//alert(xhr.responseText);
			document.getElementById("infoView").innerHTML=xhr.responseText;
		}
	}
</script>
</head>
<body>
<input type="button" value="ajaxTest" onclick="startAjax()">
<span id="infoView"></span>
</body>
</html>












반응형

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

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