728x90
[ajax]데이터 전송
화면전환 없이 데이터를 전송하기 위해 ajax를 사용하는 경우가 많다. 1. JSON 형태로 데이터 전송 1 2 3 4 5 6 7 8 9 $.ajax({ url: '데이터를 보낼 곳 url', type: 'form 태그의 method..
ddulgi.tistory.com
화면전환 없이 데이터를 전송하기 위해 ajax를 사용하는 경우가 많다.
1. JSON 형태로 데이터 전송
1
2
3
4
5
6
7
8
9
|
$.ajax({
url: '데이터를 보낼 곳 url',
type: 'form 태그의 method 속성(post 또는 get)',
data: {"변수1": "변수1의 값",
"변수2": "변수2의 값"},
success: function (data) {
alert("데이터 전송이 성공적으로 끝났을 때 실행");
}
});
|
cs |
읽을 때에는 request.getParameter로 읽으면 된다.
1
2
|
String str1 = request.getParameter("변수1");
String str2 = request.getParameter("변수2");
|
cs |
2. 폼 데이터를 한꺼번에 전송
1
2
3
4
5
6
7
8
9
|
var queryString = $('#폼id').serialize();
$.ajax({
url: '데이터를 보낼 곳 url',
type: 'form 태그의 method 속성(post 또는 get)',
data: {"폼 데이터 변수 이름": queryString},
success: function (data) {
alert("데이터 전송이 성공적으로 끝났을 때 실행");
}
});
|
cs |
읽을 때에는 폼의 각 데이터 name값으로 꺼내 읽으면 된다.
예를들어,
- form
1
2
3
4
5
6
7
|
<form id="form1">
<input type="text" name="user_name">
<input type="text" name="user_phone">
<input type="radio" value="Y" name="agree">
<input type="radio" value="N" name="agree">
<button type="button" onclick="sendFormUsingAjax()">보내기</button>
</form>
|
cs |
이런 형태의 폼 데이터를 보낸다고 하자.
보내기 버튼을 클릭하면 sendFormUsingAjax()라는 javascript 함수를 실행하게 되고, 그 안에 ajax로 데이터를 보내는 코드를 작성해두었다고 하면, 그 코드가 실행될 것이다.
보내진 곳에서 데이터를 읽는 코드는
1
2
3
|
String user_name = request.getParameter("user_name");
String user_phone = request.getParameter("user_phone ");
String agree = request.getParameter("agree");
|
cs |
form 안의 각 요소들의 name속성의 값으로 읽으면 된다.
3. 체크박스 데이터 등 배열 형태로 데이터 전송
배열 형태의 데이터를 전송할 때에는 배열데이터를 직렬화하는 코드를 작성해야 한다. ( jQuery.ajaxSettings.traditional = true )
1
2
3
4
5
6
7
8
9
10
|
var array = {1,2,3,4,5};
jQuery.ajaxSettings.traditional = true;
$.ajax({
url: '데이터를 보낼 곳 url',
type: 'form 태그의 method 속성(post 또는 get)',
data: {"배열변수": array},
success: function (data) {
alert("데이터 전송이 성공적으로 끝났을 때 실행");
}
});
|
cs |
이런 형식으로 보내고, 데이터를 읽을 때에는 배열형태의 변수를 만들고 같은 방식으로 읽으면 된다.
4.텍스트로 전송
String으로 받아진다.
function submitItem() {
if (!validateItem()) {
return;
}
let data = $("#categoryName").val();
$.ajax({
type: "POST",
url: "/category/saveCategoryName",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "text",
})
.done(function (resp) {
alert("등록이 완료되었습니다.");
location.href = "/";
})
.fail(function (error) {
alert(JSON.stringify(error));
});
}
728x90
'JQuery' 카테고리의 다른 글
Uncaught TypeError: $(...).each(...).done is not a function (0) | 2022.02.22 |
---|---|
jquery를 가져올때 (난 cdn) slim으로 가져왔다. ajax미지원 (0) | 2022.02.22 |
$ajax의 Uri 변수 경로 (0) | 2022.02.21 |
$ajax 공부 (url 주소 보낼땐 시큐리티 조심!//$ajax 통신법은 숙지!) (0) | 2022.02.14 |
JQuery(생활코딩 편) (0) | 2022.02.07 |
댓글