반응형

 jQuery에서 $를 alias로 사용하지 않도록 하는 방법

//jquery의 alias변경
var $aa = jQuery.noConflict();

$aa.ajax({});

$aa('#test').html("test입니다");

다른 라이브러리나

다른 버전의 jquery와의 충돌을 피할 수 있다.

반응형
반응형

1. binary to image

convert binary source to image

<!--HTML Source-->
<img id="imgPreview" src="">
//javascript source
let binarySrc = 'AB4AA…6HNrfUH/cbXQYCRHJ/v8HL9i0B/qBtAMAAAAASUVORK5CYII';
document.getElementById("imgPreview").src = "data:image/png;base64," + binarySrc;

 

2. binary image to file 

convert image with binary source to file

<!--image html source -->
<img id="imgPreview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB4AAAAQ3CAIAAACW5+TB">
imageToFile(document.getElementById("imgPreview").src);

function imageToFile(imgsrc){
//atob : base64로 인코딩된 src 디코딩
let bstr = atob(imgsrc.split(',')[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);

while(n--){
    u8arr[n] = bstr.charCodeAt(n);
}

let file = new File([u8arr],'imgFile.png',{type:'mime'});
console.log(file);
console.log(file.name);
//javascript 보안상 file을 input type file value에 할당할 수는 없음.
}

 

3. file to image (for previewing image )

convert file to image

shows the selected file as a preview

<!--HTML Source-->
<input type="file" id="file">
<img id="imgPreview" src="">
//파일 변경 시 미리보기 변경
$('#file').change(function(){
    readImage();
})


function readImage() {
    if(document.getElementById('file').files[0]){
        const reader = new FileReader();
        reader.onload = e => {
             const previewImage = document.getElementById('imgPreview')
             imgPreview.src = e.target.result
         }
        reader.readAsDataURL(document.getElementById('file').files[0])
}
반응형
반응형

FormData 및 <form> 으로 Javascript 데이터를 전송하기


submit 버튼으로 보내는 경우

 

1) HTML 소스

파일이 있는 경우 enctype="multipart/form-data" 로 지정해주어야 하며

파일이 없어도 상관없다.

* enctype : method가 post인 경우 enctype데이터의 MIME 타입을 말함.

<form id="testForm" action="/test" method="post" enctype="multipart/form-data">
  <input type="text" name="aa" value="11">
  <input type="text" name="bb" value="22">
  <input type="file" name="cc">
  <input type="submit">
</form>

 

2) 데이터 수신부 JAVA Controller 소스

파일이 있는 경우 파라미터 타입을 MultipartHttpServletRequest 타입으로 받고

파일이 없는 경우 HttpServletRequest 로 받는다.

@RequestMapping(value="/test", method = RequestMethod.POST)
@ResponseBody
public void test(MultipartHttpServletRequest req) throws Exception{
      String test = req.getParameter("aa");
      MultipartFile file = req.getFile("cc");
      System.out.println(test);
      System.out.println(file);
}

 

 

 
반응형

 

 

버튼에 함수 걸어서 fetch로 보내는 경우

 

1) HTML 소스

form 안에 타입 지정 안 하고 버튼을 만들면 기본값인 submit이 되어버려서 함수 거는 button은 form 밖에 만들었다.

<form id="testForm">
  <input type="text" name="aa" value="11">
  <input type="text" name="bb" value="22">
  <input type="file" name="cc">
</form>
<button onclick="submit()">완료</button>




<script>
//fetch에서 Content-Type 은 지정하지 않는다. 
function submit(){
	let myform = document.getElementById('testForm');
	formData = new FormData(myform);
	fetch('http://localhost:8001/test',{
		method:'POST',
		body : myform
	});
}
</script>

 

2) 데이터 수신부 Controller JAVA 소스 

//JAVA Controller source
//MultipartHttpServletRequest 타입으로 받는다.
@RequestMapping(value="/test", method = RequestMethod.POST)
@ResponseBody
public void test(MultipartHttpServletRequest req) throws Exception{
      String test = req.getParameter("aa");
      MultipartFile file = req.getFile("cc");
      System.out.println(test);
      System.out.println(file);
}

 

 

 

FormData 객체를 직접 만들어서 보내는 경우 

1) HTML 소스

<input type="text" id="aa" value="11">
<input type="text" id="bb" value="22">
<input type="file" id="cc">
<a onclick="submit1()">완료</a>

<script>
function submit1(){
	let formData = new FormData();
	formData.append('aa',document.getElementById('aa').value);
	formData.append('bb',document.getElementById('bb').value);
	formData.append('pic',document.getElementById('cc').files[0]);

	fetch('http://localhost:8001/test',{
		method:'POST',
		body : formData
	});

}
</script>

 

2) 데이터 수신부 Controller JAVA 소스 

//JAVA Controller source
@RequestMapping(value="/test", method = RequestMethod.POST)
@ResponseBody
public void test(MultipartHttpServletRequest req) throws Exception{
	String test = req.getParameter("aa");
	MultipartFile file = req.getFile("cc");
}

 

 

 

반응형
반응형

spring boot + thymeleaf 구조에서 resources/static 밑의 js 파일들을 사용하려고 하는데....

경로가 잘못돼서 ... 자꾸 에러가.. 났다...

Failed to load resource: the server responded with a status of 404 ()

GET http://localhost:8888/static/assets/js/mountain.js net::ERR_ABORTED 404

 

 

thymeleaf 에서의 리소스의 디폴트 경로는 /resources/static/ 이므로

static 밑의 경로부터 적어주면 잘 됨!

<script src="/assets/js/mountain.js"></script>
<script src="/js/index.js"></script>

 


관련 내용 참고

 

[SpringBoot] 정적자원관리(Resource handle) - Jongmin's Blog

정적 자원(Static Resource) 정적자원이란 html, css, image, javascript와 같이 컴파일이 필요없는 파일들을 말합니다. 스프링 부트에서 Web MVC 설정을 담당하는 WebMvcAutoConfiguration 클래스는 기본 설정으로 웹

JongMinLee0.github.io

 

반응형
반응형

url 가져오기 

> location.href
 'https://test.com?aa=1&bb=2

 

파라미터 가져오기

split을 이용하여 ?를 기준으로 앞의 url과 쿼리 스트링을 나눠준다.

> let string = location.href.split('?');
> string
 0: "https://test.com"
 1: "a=1&b=2"
 
> string[1]
 a=1&b=2

 

파라미터가 여러개라면 쿼리스트링을 &를 기준으로 나눠주면 된다.

> let params = string[1].split('&');
> params
(2) ['a=1', 'b=2']

> params[0]
'a=1'
> params[1]
'b=2'

나눠진 파라미터를 =를 기준으로 나누어서 사용하면 된다.

다소 귀찮지만 쉬운 방법.

반응형
반응형

encodeURI

일반 문자열을 인코딩하여 이스케이프 문자로 나타냄

> encodeURI("123가나다");
< '123%EA%B0%80%EB%82%98%EB%8B%A4'

 

decodeURI

encodeURI로 이스케이핑 된 문자열을 일반 문자열로 되돌린다.

> encodeURI('123%EA%B0%80%EB%82%98%EB%8B%A4');
< '123가나다'

 

location.href로 가져온 url이 인코딩되어있는 경우 사용하였다. 

반응형
반응형
//클릭한 요소 가져오기
let dv = event.currentTarget;

//클릭한 요소의 className 가져오기
dv.className;
//클릭한 요소의 style 속성 손보기
dv.style.backgroundColor;

//클릭한 요소의 하위 DOM요소 찾기(하위 요소 중 input 타입 찾기)
//input이 여러개라면 맨 처음 하나만 가져온다
dv.querySelector('input');

//특정 요소 모두 찾기
dv.querySelectorAll();

//id가 modal인 요소 찾기
dv.querySelector('#modal');

//클릭한 요소의 부모 요소 찾기
dv.parentNode;

//클릭한 요소의 자식 요소 찾기
dv.children

//자식요소가 여러개다?
dv.children[i]

//선택한 요소의 text 가져오기
dv.innerText 
dv.outerText
반응형
반응형

fetch 사용하다가...

 fetch("http://localhost:8081/startDown",{
                method : 'POST',
                 mode : 'cors',
                 cache : 'no-cache',
                 headers: {'Content-Type': 'application/json'},
                 credentials : 'same-origin',
                 redirect : 'follow',
                 referrer : 'no-referrer',
                 body: JSON.stringify(this.obj)
            }).then(response => response.text())	// 첫번째 then
              .then(res=>{ console.log(res); })	// 두번째 then

왜 위처럼 첫번째 단계에서 response.text() 한 것을 바로 사용하지 않고 .then을 한 번 더 쓰는건지 궁금했다.

왜 아래처럼 첫번째 then에서 파싱한걸 바로 사용하지 않는건지...

 fetch("url",{option}).then(response => {
            	let res = response.text();              
            
            })

이래저래 내린 결론

  • 첫 번째 then 단계에서는 response의 status 결과를 보고 어떻게 처리할지 결정할 수 있게 한다.
  • 첫 번째 단계에서는 body가 load되길 기다린다. 즉. body가 다 안 왔을 수 있다는 것. 그래서 promise를 반환한다.
  • response.text()로 파싱하는 경우 promise를 반환한다. 이 promise에 담긴 값을 사용하려면 두 번째 .then으로 받아서 promise 내부의 PromiseResult 를 사용해야 한다.

 

 

우선 promise와 .then은 이렇게 이해했다.

  • promise : 비동기 코드가 끝나면 반환된다. 비동기 처리의 상태와 데이터를 담게 되어 있다.
  • .then : 비동기 처리가 끝난 다음에 처리할 일을 정의할 수 있다.

1) fetch의 결과 출력해보기

let res = fetch("http://localhost:8081/startDown",{
                method : 'POST',
                 mode : 'cors',
                 cache : 'no-cache',
                 headers: {'Content-Type': 'application/json'},
                 credentials : 'same-origin',
                 redirect : 'follow',
                 referrer : 'no-referrer',
                 body: JSON.stringify(this.obj)
            })
console.log(res)

fetch의 결과로 Promise가 반환되었다.

pending 상태의 Promise가 찍힌것이 보이고, 화살표를 눌러 펼쳐보면 fulfilled(이행)상태가 된 것을 알 수 있다.

이행(완료)된 Promise의 Result엔 http 통신 결과로 응답 정보를 담고있는 Response Object 가 보임..

Response의 header를 보고 요청이 성공했는지 아닌지 확인 가능.

 

 

2) fetch의 결과를 .then으로 출력해보기

 fetch("",{}) //fetch url과 옵션은 생략
 	.then(console.log)

 

.then이 promise를 까서 Result인 Response object를 보여준다.

이 Response의 body를 읽으려면 response.text()나 json()같은 메소드를 사용한다.

  • status – HTTP 상태 코드(예: 200)
  • ok – 불린 값. HTTP 상태 코드가 200과 299 사이일 경우 true

 

 

3. 첫번째 then 안에서 response.text()를 한 뒤 결과물 출력해 보기

 fetch("",{ })
 	.then(response => {
                let pr = response.text();
                console.log(pr);
            })

Promise가 반환되는데, <pending>상태이지만 눌러보면 fulfilled라고 나온다. 

[i]에 이런 메세지가 보인다.

"This value was evaluated upon first expanding. It may have changed since then."

console.log가 비동기로 실행되기 때문에 console.log를 찍을 시점에는 promise가 pending 상태였으나 이후에 fulfilled 상태가 된 것을 보여준다.

 

response.text() 를 한 후 3초를 기다려서 출력해보았다

}).then(response => {
                let pr = response.text();
                setTimeout(function(){console.log(pr)},3000);
            })

아까랑 다르게 찍는 시점에서 이미 fulfilled 상태이다. 

 

 

4. 두 번째 then에서 값 출력해보기

첫 번째 .then에서 반환해준  Promise를 두 번째 .then에서 받아 PromiseResult에 담긴 값을 사용한다.

response.text() 후에 .then에서 값을 출력해보면

PromiseResult의 값이 출력되었다

fetch("",{})
	.then(response => response.text())
	.then(console.log)


참고 

 

fetch

 

ko.javascript.info

 

 

프라미스(Promise)

0px Promise는 무엇인가? Promise의 state와 result Promise chaining return Promise Error handling Promise API async, await Promise는 무엇인가? 단어 그대로 약속(promise)입니다. 어떤 약속이냐면 어떠한..

snowboolean.tistory.com

 

 

fetch() 함수 사용법 - Blog by Yeri

백앤드로부터 데이터를 받아오려면 api를 호출하고 데이터를 응답받습니다. 이 때 자바스크립트 Web API fetch() 함수를 쓰거나 axios 라이브러리를 사용할 수 있습니다. 참고로 Web API는 클라이언트

yeri-kim.github.io

 

 

 

Why is the response object from JavaScript fetch API a promise?

When requesting from a server with JavaScript fetch API, you have to do something like fetch(API) .then(response => response.json()) .catch(err => console.log(err)) Here, response.json(...

stackoverflow.com

 

반응형
반응형

AJAX 코드 

  • success : url 호출에 대한 응답 코드가 2xx인 경우

기본적으datastatusText, jqXHR 세 개의 파라미터가 있다.

 

  • error : url 호출에 대한 응답 코드가 2xx가 아닌 경우

error의 경우도 jqXHR, textStatus, errorThrown 세 개의 파라미터를 가진다.

jqXHR : 서버에서 responseEntity에 담아서 보낸 응답 메시지로, 데이터 내부에서 응답 텍스트와 응답 코드를 확인할 수 있다.

errorThrown :  응답코드의 텍스트 이름이라고 한다.(근데 나는 안 뜸)

 $.ajax({
 	type: "post",
	url : "http://localhost:8080/donwnload",
	headers: {'Content-Type': 'application/json'},
	data : JSON.stringify(obj),
                    
	success : function (data, statusText, jqXHR){
		console.log(data); //응답 body부 데이터
		console.log(statusText); //"succes"로 고정인듯함
		console.log(jqXHR);
	},
                    
	error : function (jqXHR, textStatus, errorThrown){
		console.log(jqXHR);  //응답 메시지
		console.log(textStatus); //"error"로 고정인듯함
		console.log(errorThrown);
	}
})

 

error function의 jqXHR

  • responseText : ResponseEntity 응답 메시지로 보낸 텍스트 ( jquery 1.4.x 버전은 XMLHttpRequest로 표시)
  • status : 응답코드

 


참고

 

jQuery.ajax() | jQuery API Documentation

Description: Perform an asynchronous HTTP (Ajax) request. The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available

api.jquery.com

 

반응형
반응형

JavaScript에서 AJAX 나 Fetch로 JSON 데이터 전송, SpringBoot의 Controller에서 데이터 받기


 

AJAX로 데이터 전송하기  : Content -Type  지정하지 않은 경우

 

1) javascript 

Content Type을 명시하지 않으면 기본 타입은 application/x-www-form-urlencoded 으로 전송된다. 

let obj={
	"fromYear" : $('#fromYear').val(),
	"fromMonth" : $('#fromMonth').val(),
	"fromDay" : $('#fromDay').val(),
	"toYear" : $('#toYear').val(),
	"toMonth" : $('#toMonth').val(),
	"toDay" : $('#toDay').val()
};


$.ajax({
        type: "post",
        url : "http://localhost:8080/test2",
        data : obj,
        success : function (data){
        },
})

 

2) 전송되는 데이터 확인

요청 헤더의 Content-Type 은 application/x-www-form-urlencoded; charset=UTF-8 이며

body의 데이터가 FormData로 표시된다. 

 

3) 데이터 수신 Controller 

파라미터는 변수명이나 VO로 받는다.

@RequestMapping(value = "/test2", method = RequestMethod.POST)
@ResponseBody
public void test2(String fromYear, String fromMonth, String fromDay,String toYear, String toMonth, String toDay){
	System.out.println(fromYear+fromMonth+fromDay);
	//2021825
}

 

혹은 HttpServletRequest로 받는다.

HttpServletRequest로 받는 경우 데이터를 좀 가공함.

@RequestMapping(value = "/test2", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Resource> test(HttpServletRequest req)throws IOException{
	//readBody 메소드 호출
	String body = readBody(req);
	System.out.println(readBody(req));
	//fromYear=2021&fromMonth=8&fromDay=25&toYear=2021&toMonth=8&toDay=25

	//String 으로 바꾼 body부를 JSON형태로 변환하여 사용
	org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser();
	Object obj = parser.parse(body);
	JSONObject jsonObj = (JSONObject) obj;
	String fromYear = (String) jsonObj.get("fromYear");
    
	return new ResponseEntity<>("성공", HttpStatus.OK);
}


//body 읽는 메소드
public static String readBody(HttpServletRequest request) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String buffer;
        while ((buffer = input.readLine()) != null) {
            if (builder.length() > 0) {
                builder.append("\n");
            }
            builder.append(buffer);
        }
        return builder.toString();
}

 

 


 

반응형

 

 

AJAX로 데이터 전송하기  : Content -Type  을 JSON으로 보내는 경우

 

1) javascript 

보낼 데이터를 JSON.stringify()로 감싸주어야 한다.

$.ajax({
        type: "post",
        url : "http://localhost:8080/test2",
        headers: {'Content-Type': 'application/json'},
        ///보낼 데이터를 JSON.stringify()로 감싸주어야 함
        data : JSON.stringify(obj),
        success : function (data){
        	console.log(data);
        },
        error : function(e){
        }
})

 

2) 전송되는 데이터 확인

요청 헤더의 Content-Type은 application/json이며

body의 데이터가 Request Payload로 표시된다

 

 

3) 데이터 수신 Controller 

 파라미터를 HttpServletRequest로 받는다.

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Resource> test(HttpServletRequest req)throws IOException{
	System.out.println(readBody(req));
 	//{"fromYear":"2021","fromMonth":"8","fromDay":"25","toYear":"2021","toMonth":"8","toDay":"25"}
}


public static String readBody(HttpServletRequest request) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String buffer;
        while ((buffer = input.readLine()) != null) {
            if (builder.length() > 0) {
                builder.append("\n");
            }
            builder.append(buffer);
        }
        return builder.toString();
}

 


 

fetch로 데이터 전송하기

 

1) javascript 

fetch("http://localhost:8080/test",{
                    method : 'POST',
                    mode : 'cors',
                    cache : 'no-cache',
                    //Content Type은 json으로 명시한다.
                    headers: {'Content-Type': 'application/json'},
                    credentials : 'same-origin',
                    redirect : 'follow',
                    referrer : 'no-referrer',
                    body: JSON.stringify(obj),
}).then(response => console.log(response));

 

2) 전송되는 데이터 확인

request payload로 전송이됨

 

 

3) 데이터 수신 Controller

파라미터는 HttpServletRequest로 받는다.

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Resource> test(HttpServletRequest req)throws IOException{
	System.out.println(readBody(req));
	//{"fromYear":"2021","fromMonth":"8","fromDay":"25","toYear":"2021","toMonth":"8","toDay":"25"}
}


public static String readBody(HttpServletRequest request) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String buffer;
        while ((buffer = input.readLine()) != null) {
            if (builder.length() > 0) {
                builder.append("\n");
            }
            builder.append(buffer);
        }
        return builder.toString();
}

 

 

 


참고

 

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

I have an old web application I have to support (which I did not write). When I fill out a form and submit then check the "Network" tab in Chrome I see "Request Payload" where I would normally see...

stackoverflow.com

 

반응형

+ Recent posts