[javaScript] Ajax(1)

seonjeongยท2023๋…„ 2์›” 7์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
6/8
post-thumbnail

๐Ÿ”ฅ Ajax๋ž€?

  • Asynchronous Javascript And Xml(Json)
  • ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์„œ๋ฒ„์—๊ฒŒ ๋น„๋™๊ธฐ ๋ฐฉ์‹์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์š”์ฒญํ•˜๊ณ , ์„œ๋ฒ„๊ฐ€ ์‘๋‹ตํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์‹ ํ•˜์—ฌ ์›นํŽ˜์ด์ง€๋ฅผ ๋™์ ์œผ๋กœ ๊ฐฑ์‹ ํ•˜๋Š” ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๋ฐฉ์‹
  • ํ•„์š”ํ•œ ๋ถ€๋ถ„๋งŒ ๋น„๋™๊ธฐ ๋ฐฉ์‹์œผ๋กœ ์ „์†ก๋ฐ›์•„ ๋ณ€๊ฒฝํ•  ํ•„์š”๊ฐ€ ์žˆ๋Š” ๋ถ€๋ถ„๋งŒ ํ•œ์ •์ ์œผ๋กœ ๋ Œ๋”๋ง

๐Ÿ”ฅ jQuery ์ด์šฉ

๐Ÿงพ JSON

<p id="demo"></p>
<button type="button">button</button>
  • javascript
$("button").click(function() {
	$.ajax({
    	// ์ „์†ก
      	url:"data.json",	// ์–ด๋””๋กœ ๊ฐˆ์ง€
      	type:"get",			// ํ˜•์‹ 
      	datatype:"json",	// ํƒ€์ž…
      
      	// ์ˆ˜์‹ 
      	success:function(data){	// ํŒŒ์ผ ์ฐพ๊ธฐ ์„ฑ๊ณต		
          for(let i = 0; i < data.length; i++) {
          	$("#demo).append(data[i].name + " ");
            $("#demo).append(data[i].age + " ");
            $("#demo).append(data[i].address + " ");
            $("#demo).append(data[i].phone + " ");
          },
          error:function() {
          	alert("error");
          }
        
        }
    });
});
  • json
[
	{
		"name":"ํ™๊ธธ๋™",
		"age":24,
		"address":"์„œ์šธ์‹œ",
		"phone":"123"
	},
	{
		"name":"์„ฑ์ถ˜ํ–ฅ",
		"age":16,
		"address":"๋‚จ์›์‹œ",
		"phone":"234"
	},
	{
		"name":"ํ™๋‘๊ป˜",
		"age":22,
		"address":"๊ฐ•๋ฆ‰์‹œ",
		"phone":"345"
	}
]

๐Ÿงพ JSP

<p id="name"></p>
<p id="age"></p>
<p id="birth"></p>
  • javascript
$(function() {
	$("button").click(function() {
    	$.ajax({
        	url:"data.jsp",
          	type:"get",
          	datatype:"json",
          	success:function(data) {
            	let json = JSON.parse(data);
              
              	$("#name").text(json.name);
                $("#age").text(json.age);
                $("#birth").text(json.birth);  
            },
          	error:function() {
            	alert("error");
            }
        });
    });
});
  • jsp
<%
// JDBC -> ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฐ์ถœ

String name = "ํ—ˆ๊ด‘ํ•œ"
int age = 34;
String birth = "1990/10/31";

// json + ๋‚ด์žฅ๊ฐ์ฒด
String str = "{\"name\":\"" + name + "\", \"age\":\"" + age + "\", \"birth\":\"" + birth + "\"}"

out.println(str);
%>
profile
๐Ÿฆ‹๊ฐœ๋ฐœ ๊ณต๋ถ€ ๊ธฐ๋ก๐Ÿฆ‹

0๊ฐœ์˜ ๋Œ“๊ธ€