티스토리 뷰

 

1. 단순하게 보내기 

 

		var formsubmit = $("#form").serialize();
		
        $.ajax({
		    url: "/googlechartAjax",
		    type: "post",
		    dataType: "json",
		    data: formsubmit,
		    success: function(json){
		    	var texts = json[0].text1
		    	 $('#innerstart').text("");
		   	},
		    error: function (request, status, error){    
		    	console.log(status);
		    	$('#innerstart').text("");
		    }

		  });

주의할 점은 
contentType: "application/json; charset=utf-8", 

을 써주면 안된다. 쓰면 에러난다. 

@ResponseBody
	@RequestMapping(value = "/googlechartAjax", method = RequestMethod.POST, produces = "application/text; charset=utf8")
	public String googlechartAjax(
			GoogleVo vo) throws Exception {
            JSONObject json = new JSONObject();
            return json.toString;
            }

 

2. RequestBody를 쓰고싶다면

 

function objectifyForm(formArray) {//serializeArray data function
		var returnArray = {};
		for (var i = 0; i < formArray.length; i++) {
			returnArray[formArray[i]['name']] = formArray[i]['value'];
		}
		return returnArray;
	}

위의 기능을 미리 써야한다. 

		var formsubmitSerialArray = $("#form").serializeArray();
		var formsubmit = JSON.stringify(objectifyForm(formsubmitSerialArray));

$.ajax({
					url : "/주소",
					type : "POST",
					accept : "application/json",
					contentType : "application/json; charset=utf-8",
					dataType : "json",
					data : formsubmit,
					success : function(json) {
						console.log(json);

					},
					error : function(request, status, error) {
						console.log(status);
						
					}

				});

var formsubmitSerialArray = $("#form").serializeArray();
var formsubmit = JSON.stringify(objectifyForm(formsubmitSerialArray));

이 두줄이 핵심인데 serializeArray로 array화 된 form을 objectifyForm이 json으로 변환한다.

이를stringify로 string화 시켜서 보낸다. 

 

 

@ResponseBody
	@RequestMapping(value = "/googlechartAjax", method = RequestMethod.POST, produces = "application/json; charset=utf8")
	public String googlechartAjax(
			@RequestBody GoogleVo vo
			) throws Exception {
            	JSONObject json = new JSONObject();
	
			return json.toString();
	}

이렇게 하면 RequstBody를 사용할 수 있다. 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함