교육47일차

권재현·2021년 5월 27일
0

교육

목록 보기
33/49

Ajax - 비동기 방식의 전송방식

  • 동기화(synchronize) - 주소와 화면 일치, 앞에서처리
  • 비동기화(Asynchronize) - 주소와 화면이 별개로 인식, 뒤에서 처리

주는 것 --> 데이터

받는 것 --> 결과 데이터

Ajax에서의 데이터

  • 문자열
  • json --> javascript object를 문자열화
  • xml --> 정보를 tag형태로 관리

test.json 파일만들기( 그냥 파일로 만들어야된다.)

ajaxTest만들기

TestController 추가

파일 위치

날씨 api 사용하기

test.json

{
	"list" : [
		{
				"no" : "1",
				"name" : "홍길동" 	
		},
		{
				"no" : "2",
				"name" : "김철수"
		},
		{
				"no" : "3",
				"name" : "박대리"
		}
	]
}

ajaxTest

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>날씨 api</title>
<style type="text/css">
#weatherIcon{
	display: none;
}
</style>
<script type="text/javascript"
	src="resources/jquery/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$("#weatherIcon").hide();
	
	getWeather();
	
	$("#getBtn").on("click", function(){
		$.ajax({
			url: "resources/json/test.json", // 접속 주소
			type: "get", // 전송방식 : get,post
			dataType: "json", // 받아올 데이터 형식
			success: function(res){ //성공 시 다음 함수 실행 
				var html= "";
				
				for(var d of res.list) {
					html += d.no +"," + d.name + "<br/>"
				}
				
				$("#box").append(html)
			},
			error: function(request, status, error){ //실패 시 다음 함수 실행
				console.log(request);				
				console.log(status);				
				console.log(error);				
			}
		});
	});
});
function getWeather(){
	$.ajax({ //get 방식은 ? 기준으로 주소와 데이터가 나뉜다.
		url: "http://api.openweathermap.org/data/2.5/weather", // 접속 주소
		type: "get", // 전송방식 : get,post
		dataType: "json", // 받아올 데이터 형식
		data: "q=seoul&appid=f532aa01d351de228cbeb0be0c5d16b0&lang=kr&units=metric", 
        //보낼 데이터(문자열 형태)
		success: function(res){ //성공 시 다음 함수 실행 
			console.log(res);
			console.log(res.main.temp);
			console.log(res.weather[0].icon);
			$("#weatherIcon").attr("src",
					" http://openweathermap.org/img/wn/"
					+ res.weather[0].icon + "@2x.png");
			
			$("#temp").html(res.main.temp +"℃-"+ res.weather[0].description);
			$("#weatherIcon").fadeIn("slow");
		},
		error: function(request, status, error){ //실패 시 다음 함수 실행
			console.log(request);				
			console.log(status);				
			console.log(error);				
		}
	});
}
</script>
</head>
<body>
<div id="weatherWrap">
<img alt="날씨" id="weatherIcon" />
<br/>
<span id="temp"></span>
</div>
<input type="button" value="가져오기" id="getBtn"/>
<div id="box"></div>
</body>
</html>

TestController

	package com.test.spring.test.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {
	
	@RequestMapping(value="/test1")
	
	/*
	 * ModelAndView : 데이터와 뷰를 담을 수 있는 클래스
	 */
	public ModelAndView test1(ModelAndView mav) {
		
		//ViewResolver : "/WEB-INF/views/test/test1.jsp"
		mav.setViewName("test/test1"); //jsp 위치지정
		
		return mav;
	}
	//@HttpServletRequest : 요청과 관련된 데이터 집합(사용자에서 넘어온것)
	//@RequestParam(value=값)변수타입 변수명 : 값에 해당하는 key가 넘어올때 
					  //Key에 연결된 값을 변수에 담는다.
	//@RequestParam 변수타입 변수명 : 변수명과 동일한 Key가 넘어올 때
	//			        Key에 연결된 값을 변수에 담는다.
	//@RequestParam HashMap : 넘어오는 Key와 Value들을 Map에 담는다.
	//@RequestParam(value=값) List 변수명 : 값에 해당하는 Key들이 넘어올 때
	//	List는 체크박스 쓸대만 사용 Key에 연결된 값들을 리스트에 담는다.
	// HttpServletResponse:  응답에 대한 정보(보낼형태, 헤더정보)
	@RequestMapping(value="/test2")
	public ModelAndView test2(HttpServletRequest req,
			@RequestParam(value="txt") String s,			
			@RequestParam String txt,
			@RequestParam HashMap<String, String> params,
			@RequestParam (value="txt") ArrayList<String> list,
									ModelAndView mav) {
		
		System.out.println(req.getParameter("txt"));
		System.out.println(s);
		System.out.println(txt);
		System.out.println(params.get("txt"));
		System.out.println(list.get(0));
		
		//req.setAttribute("test", "Hi~");
		
		mav.addObject("test", "Hi2!!"); // Model에 값을 담는다
		
		List<HashMap<String, String>> data 
				= new ArrayList<HashMap<String, String>>();
		
		for(int i = 10; i > 0 ; i--	) {
			HashMap<String, String> temp
				= new HashMap<String, String>();
			
			temp.put("no", Integer.toString(i));
			temp.put("title","test" + i);
			
			data.add(temp);
		}
		mav.addObject("data", data);		
		
		mav.setViewName("test/test2");
		//setViewName : 파일여기있다고 열라고주는 거,경로만 알려줌,src랑 같은역활
		return mav;
	}
		// 주소가 생길때 마다 아래 형식을 만들어준다.
	@RequestMapping(value="/ajaxTest")
	public ModelAndView at(ModelAndView mav) {
		
		mav.setViewName("test/ajaxTest");

		return mav;
	}
	
}

이모지 윈도우 + .

출력결과

profile
호텔리어 출신 비전공자

0개의 댓글