jqueryとサーバPOST

20323 ワード

ajaxPOST.html
送信したいデータをオブジェクトとして作成し、paramデータに送信すればよい.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
	function reqList(){
		var param = {};
		param.name = "홍길동";
		param.tel = "010-7777-8888";
		param.address = "율도국";
		
		$.ajax({
			url : "/Contact/add.do",
			type : "POST",
			data : param,
			success : function(data){
				console.log(data);
				$("#resp").html(data);
			}
		});
	}
	function delList(){
		$("#resp").html("");
	}
</script>
</head>
<body>
	<button type="button" onclick="reqList();">요청</button>
	<button type="button" onclick="delList();">삭제</button>
	<p id="resp"></p>
</body>
</html>
結果

ajaxJSON.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
	function reqList(){
		var send_data = {
				contacts : [
					{no:64, name:'오바마', tel:'8282', address:'워싱턴'},
					{no:63, name:'힐러리', tel:'8282', address:'워싱턴'},
					{no:62, name:'샌더스', tel:'8282', address:'워싱턴'},
					{no:61, name:'트럼프', tel:'8282', address:'워싱턴'},
					{no:60, name:'바이든', tel:'8282', address:'워싱턴'}
				]
		};
		
		/*
		JSON.stringify = js객체를 문자열로 전환 
		JSON.parse = 문자열을 js객체로 전환 
		*/
		
		$.ajax({
			url : "/Contact/update_batch.do",
			type : "POST",
			// json 데이터를 보내므로 써줘야 한다 
			contentType : "application/json",
			data : JSON.stringify(send_data),
			success : function(data){
				console.log(data);
				$("#resp").html(data);
			}
		});
	}
	function delList(){
		$("#resp").html("");
	}
</script>
</head>
<body>
	<button type="button" onclick="reqList();">요청</button>
	<button type="button" onclick="delList();">삭제</button>
	<p id="resp"></p>
</body>
</html>
結果