티스토리 뷰

HTML \ CSS

jQuery - ajax()

Lea_rlo 2022. 4. 9. 21:54

ajax() 함수는 KEY : VALUE 형식으로 작성한다.

 

 

 

1. GET방식으로 KEY=VALUE 형식의 데이터를 보내기

$.ajax({
	type : "GET", //default get이라 생략 가능
    url : "http://localhost:8080/test?username=Lea&password=123",
    //data: 쿼리 스트링으로 데이터를 보내기 때문에 data 설정 못함
    //contentType:전송할 데이터가 없기 때문에 요청 데이터 타입을 설정하지 않아도 됨
    //dataType:"text" 응답 타입에 따라 설정 가능함 기본 text로 오기 때문에 생략 가능
})

 

결론 : 아래와 같이 작성할 수 있다. 

$.ajax({
	url:"http://localhost:8080/test?username=lea&password=123"
})

 

2. POST 방식으로 KEY=VALUE 형식의 데이터 보내기

$.ajax({
                type: "POST",
                url: "http://localhost:8080/ajax1",
                data: "username=lea&password=1234",
                contentType: "application/x-www-form-urlencoded",
                dataType: "json"
})

 

application/x-www-form-urlencoded은 POST 방식이다. 생략하면 기본 설정이 application/x-www-form-urlencoded이다. 보내는 데이터가 없을 때에도 application/x-www-form-urlencoded로 기본 설정되어있다.

 

application/json은 {key: value}의 형태로 전송하고  application/x-www-form-urlencoded는 key=value&key=value의 형태로 전송한다. 위 코드의 data 형식을 보면 = & = 형식으로 데이터를 보낸다.

 

응답 타입(dataType)은 json으로 설정했다.  JS 오브젝트 타입으로 파싱된다. JS에서 응답 받을 데이터 타입을 설정하지 않고 Java에서 response의 setContentType() 메소드로 응답 데이터를 설정해줄 수 있다. 

 

 

https://api.jquery.com/jquery.ajax/

 

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

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types

MIME 타입에 대해 공부하자. 

 

MIME types (IANA media types) - HTTP | MDN

A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) indicates the nature and format of a document, file, or assortment of bytes. MIME types are defined and standardized in IETF's RFC 6838.

developer.mozilla.org

 

'HTML \ CSS' 카테고리의 다른 글

CodePen을 사용해보자  (0) 2022.04.09
처음으로 작성하는 티스토리 글  (0) 2022.04.09
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함