ajax 에서 배열을넘겨 JAVA 에서 확인할수있다
traditional 옵션을 넣어주면 간단하게 되는거지만
대부분 삽질을 하게된다
1.javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var arr = ['aa', 'bb', 'cc']; $.ajax({ method : 'POST', url : 'test.do', traditional : true, data : { 'main' : arr }, success : function(data) { alert(data); }, error : function(request, status, error) { alert(error); } }); Colored by Color Scripter |
cs |
2.JAVA
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 |
@RequestMapping(value = "/test.do", method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView test( HttpServletRequest request, String[] main//배열 받기 traditional: true ) { view.setViewName("jsonView"); try { System.out.println(main[0]+"===============");//aa System.out.println(main[1]+"===============");//bb System.out.println(main[2]+"===============");//cc System.out.println(main[3]+"===============");//errer //throw new Exception(); view.addObject("result", "success"); }catch(Exception ex){ ex.printStackTrace(); } return view; } Colored by Color Scripter |
cs |
Ajax를 이용하면 웹 어플리케이션과 비동기적으로 데이터를 주고 받은후 클라이언트에서 해당 데이터에 대한 처리를 할 수 있다. 쉽게 이야기하면 Ajax를 이용할 경우 별도의 웹 페이지를 호출하지 않더라도, 클라이언트 화면을 유지한채 다른 페이지를 호출할 수 있다.
Ajax에 대한 설명은 위키백과를 참고하기 바란다. - http://ko.wikipedia.org/wiki/Ajax
이러한 Ajax를 jQuery를 이용하면 정말 손쉽게 사용할 수 있는데, 기본적인 설정값만 넣어주면 바로 사용이 가능하다.
다음 예제는 웹페이지가 로딩된 후 ajax를 이용하여 ajaxData.jsp를 호출하는 예제이다.
ajaxData.jsp는 텍스트 형식의 값을 리턴하며 리턴된 값을 alert창과 div에 출력한다.
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 31 32 33 34 35 36 37 38 39 40 41 42 |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax 간단 테스트</title> <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function(){ $.ajax({ type : "GET", url : "ajaxData.jsp?type=1", dataType : "text", error : function(){ alert('통신실패!!'); }, success : function(data){ alert("통신데이터 값 : " + data) ; $("#dataArea").html(data) ; } }); }); </script> </head> <body> <div id="dataArea"></div> </body> </html> |
위의 예제는 ajax 통신을 할때 가장 기본이 되는 항목만 사용하였다. 적어도 위의 설정값 정도는 최소한으로 넣어주는게 좋다.
속성 | 설명 |
type | http 전송 method를 지정한다. GET, POST |
url | 호출 URL. GET 방식일경우 URL 뒤에 파라미터를 붙여서 사용해도 된다. |
dataType | Ajax를 통해 호출한 페이지의 Return 형식이다. 형식에 따라 xml, json, html, text 등을 사용하면 된다. |
error | 에러났을때의 처리 부분이다. |
success | 성공했을때의 처리 부분이다. 보통 해당 부분에서 데이터 핸들링을 하면 된다. |
- 각 Ajax 방식을 호출하는 방법
view plaincopy to clipboardprint?
- // 버튼 클릭시 ajax 실행
- $("#btnOK").click(function(){
- var url="test.aspx";
- var params="param1="+param1+"¶m2="+param1;
- $.ajax({
- type:"POST",
- url:url,
- data:params,
- success:function(args){
- $("#result").html(args);
- },
- beforeSend:showRequest,
- error:function(e){
- alert(e.responseText);
- }
- });
- });
1. $.post() 방식
- 서버에 데이터를 HTTP POST 방식으로 전송한 후 서버측 응답 받을 때 사용
[형식]
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
- url : 요청 Url
- data : 요청과 함께 서버에 보내는 string 또는 map
- success(data,textStatus,jqXHR) : 요청이 성공일때 실행되는 callback 함수
- dataType : 서버에서 내려온 data 형식. ( default : xml,json,script,text,html )
[$.ajax 로 표현]
view plaincopy to clipboardprint?
- $.ajax({
- type: 'POST',
- url: url,
- data: data,
- success: success,
- dataType: dataType
- });
[사용예]
view plaincopy to clipboardprint?
- // 요청 Url 만 , 리턴 결과값 무시
- $.post("http://web/test/");
- // 요청 Url + 추가적으로 보내는 Json Data, 리턴 결과값 무시
- $.post("http://web/test/", { name: "John", time: "2pm" } );
- // 요청 Url + 추가적으로 보내는 Array Data, 리턴 결과값 무시
- $.post("http://web/test/", { 'choices[]': ["Jon", "Susan"] });
- // 요청 Url + 폼데이터, 리턴 결과값 무시
- $.post("http://web/test/", $("#testform").serialize());
- // 요청 Url, xml(또는 html)리턴 결과값
- $.post("http://web/test/",
- function(data) { alert("Data Loaded: " + data); });
- // 요청 Url + 추가적으로 보내는 Json Data, 리턴결과값, 결과값 형식
- $.post("http://web/test/", { name: "John", time: "2pm" },
- function(data) { process(data); }, "xml" );
- // 요청 Url + 추가적으로 보내는 Json Data, 리턴결과값(json 다루는 형식), 결과값 형식
- $.post("http://web/test/", { "func": "getNameAndTime" },
- function(data){
- console.log(data.name); // John
- console.log(data.time); // 2pm
- }, "json");
2. $.get() 방식
- 서버에 데이터를 HTTP GET 방식으로 전송한 후 서버측 응답 받을 때 사용
[형식]
jQuery.get( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
- url : 요청 Url
- data : 요청과 함께 서버에 보내는 string 또는 map
- success(data,textStatus,jqXHR) : 요청이 성공일때 실행되는 callback 함수
- dataType : 서버에서 내려온 data 형식. ( default : xml,json,script,text,html )
[$.ajax 로 표현]
view plaincopy to clipboardprint?
- $.ajax({
- url: url,
- data: data,
- success: success,
- dataType: dataType
- });
[사용예]
view plaincopy to clipboardprint?
- // 요청 Url 만 , 리턴 결과값 무시
- $.get("http://web/test/");
- // 요청 Url + 추가적으로 보내는 Json Data, 리턴 결과값 무시
- $.get("http://web/test/", { name: "John", time: "2pm" } );
- // 요청 Url + 추가적으로 보내는 Array Data, 리턴 결과값 무시
- $.get("http://web/test/", { 'choices[]': ["Jon", "Susan"] });
- // 요청 Url, xml(또는 html)리턴 결과값
- $.get("http://web/test/", function(data) { alert("Data Loaded: " + data); });
- // 요청 Url + 추가적으로 보내는 Json Data, 리턴결과값, 결과값 형식
- $.get("http://web/test/", { name: "John", time: "2pm" }, function(data) { process(data); }, "xml" );
- // 요청 Url + 추가적으로 보내는 Json Data, 리턴결과값(json 다루는 형식), 결과값 형식
- $.get("http://web/test/", { "func": "getNameAndTime" }, function(data){ console.log(data.name); // John console.log(data.time); // 2pm }, "json");
3. $.getJSON() 방식
- 서버에 데이터를 HTTP GET 방식으로 전송한 후 서버측 응답을 JSON 형식으로 받을때 사용
[형식]
jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
- url : 요청 Url
- data : 요청과 함께 서버에 보내는 string 또는 map
- success(data,textStatus,jqXHR) : 요청이 성공일때 실행되는 callback 함수
[$.ajax 로 표현]
view plaincopy to clipboardprint?
- $.ajax({
- url: url,
- dataType: 'json',
- data: data,
- success: callback
- });
[사용예]
view plaincopy to clipboardprint?
- <script>
- $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
- {
- tags: "mount rainier",
- tagmode: "any",
- format: "json"
- },
- function(data) {
- $.each(data.items, function(i,item){
- $("<img/>").attr("src", item.media.m).appendTo("#images");
- if ( i == 3 ) return false;
- });
- });
- </script>
4. $.ajax() 방식
- 서버에 데이터를 HTTP POST,GET,JSON 모든 방식 전송 가능한 통합적인 함수
- 다양한 Parameter 존재
[형식]
jQuery.ajax( url [, settings] ) [ 1.5 이상버젼 ] ,jQuery.ajax( settings ) [ 1.0 이상버젼 ]
- url : 요청 Url
- settings : key/value 쌍으로 된 Ajax 요청 Set ( optional )
[사용예]
view plaincopy to clipboardprint?
- // 요청 Url + 추가적 데이터, 완료된 후 리턴 메시지를 받음
- $.ajax({
- type: "POST",
- url: "http://web/test/",
- data: { name: "John", location: "Boston" }
- }).done(function( msg ) {
- alert( "Data Saved: " + msg );
- });
- // 최종 버전 리턴 Html 가져오기
- $.ajax({
- url: "http://web/test/",
- cache: false
- }).done(function( html ) {
- $("#results").append(html);
- });
- // 서버에 데이터를 보낸 후 저장처리, 그리고 사용자에게 리턴 완료 메시지 반환
- var menuId = $("ul.nav").first().attr("id");
- var request = $.ajax({
- url: "http://web/test/",
- type: "POST",
- data: {id : menuId},
- dataType: "html"
- });
- request.done(function(msg) {
- $("#log").html( msg );
- });
- request.fail(function(jqXHR, textStatus) {
- alert( "Request failed: " + textStatus );
- });
- // 자바 스크립트 로딩 및 실
- $.ajax({
- type: "GET",
- url: "test.js",
- dataType: "script"
- });
4.1 $.ajaxSetup()
- 공통적인 기본 ajax 요청을 미리 설정함
[형식]
jQuery.ajaxSetup( options )
- optional : default Ajax 요청의 설정값 ( key/value )
[사용예]
view plaincopy to clipboardprint?
- // 미리 ajaxSetup에 기본사항들을 설정한 후 ajax 로 각각 호출
- $.ajaxSetup({
- url: 'http://web/test/',
- global: false,
- type: "POST"
- });
- $.ajax({
- // url not set here; uses 'http://web/test/'
- data: {'name': 'Dan'}
- });
- $.ajax({
- // url not set here; uses 'http://web/test/'
- data: {'name': 'John'}
- });
5. $.load() 방식
- 외부 컨텐츠 가져올때 사용
[형식]
.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
- url : 요청 Url
- data : 요청과 함께 서버에 보내는 string 또는 map
- complete(responseText, textStatus, XMLHttpRequest) : 요청이 완료될때 실행되는 callback 함수
[사용예]
view plaincopy to clipboardprint?
- // Html Content 로딩
- $('#result').load('ajax/test.html');
- // Html Content 로딩 후 메시지
- $('#result').load('ajax/test.html', function() {
- alert('Load was performed.');
- });
- // Html Content #container Target 로딩
- $('#result').load('ajax/test.html #container');
- // array parameter 전달 후 Html Content 로딩
- $("#objectID").load("test.asp", { 'choices[]': ["Jon", "Susan"] } );
출처: https://killsia.tistory.com/entry/jquery-ajax-방법 [One Day One Line]
출처: https://epthffh.tistory.com/entry/ajax-배열전송 [물고기 개발자의 블로그]
'웹개발 > 기타' 카테고리의 다른 글
암호와 종류 (양방향 / 단방향) (0) | 2022.02.17 |
---|---|
log4j 파일별 특정 로그 제외하거나 특정 데이터만 쌓는 방법 (0) | 2022.02.17 |
GNU / GPL 라이센스 (0) | 2021.08.02 |
Internet Explorer에서 addEventListener, createElement, $, jquery 등등 오류 시 (0) | 2021.07.29 |
javascript 그림판 라이브러리 (0) | 2021.07.29 |
댓글