๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’š ๊ฐœ๋ฐœ/์›น

javascript ์—์„œ ajax๋ฅผ ์ด์šฉํ•ด ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ json format์œผ๋กœ ํ•˜๋‚˜๋กœ ๋ฌถ์–ด์„œ ์ธ์ฝ”๋”ฉํ•ด ์„œ๋ฒ„๋กœ ์ „์†กํ•˜๋Š” ๋ฐฉ๋ฒ•

by devshin.kr 2020. 11. 5.
728x90

javascript ์—์„œ ajax๋ฅผ ์ด์šฉํ•ด ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ json format์œผ๋กœ ํ•˜๋‚˜๋กœ ๋ฌถ์–ด์„œ ์ธ์ฝ”๋”ฉํ•ด ์„œ๋ฒ„๋กœ ์ „์†กํ•˜๋Š” ๋ฐฉ๋ฒ•

(๊ตฌ๊ตฌ์ ˆ์ ˆ)

 

๋ณธ์ธ์˜ ๊ธฐ์–ต์šฉ ๊ฒŒ์‹œ๊ธ€์ž„. ใ…‡ใ…‡

---- ํด๋ผ ---- javascript

// ์„œ๋ฒ„๋กœ ๋ณด๋‚ผ ๊ฐ’
var data1 = "hello";
var data2 = "world";

// json format ๋งŒ๋“ค์–ด key : value ์Œ์œผ๋กœ ๋งŒ๋“ค์–ด ์ฃผ๊ธฐ
var jsonData = new Object();
jsonData.key1 = data1;
jsonData.key2 = data2;

// ์œ„์—์„œ ๋งŒ๋“  json format์„ ๋ฌธ์ž์—ดํ™”
var sendData = JSON.stringify(jsonData);

// ์„œ๋ฒ„๋กœ ์ „๋‹ฌ
$.ajax({
    url:'๊ฐ’์„ ์ „๋‹ฌ ๋ฐ›์„ ์„œ๋ฒ„์˜ ์ฃผ์†Œ'+"?data="+encodedURIComponent(sendData),
    success : function(retData){
        var resObj = JSON.parse(retData);
        alert(resObj.ret1);   // 123 ์ถœ๋ ฅ
        alert(resObj.ret2);   // 456 ์ถœ๋ ฅ
    }
});

 

 

---- ์„œ๋ฒ„ ---- java

// ํด๋ผ๋กœ๋ถ€ํ„ฐ ์˜จ ๊ฐ’
String theParams = request.getParameter("data");

JSONParser parser = new JSONParser();
Object obj = parser.parse(theParams);
JSONObject jsonObj = (JSONObject)obj;

// ํด๋ผ๋กœ๋ถ€ํ„ฐ ๋ฐ›์•„ ์˜จ ๊ฐ’ ์ถœ๋ ฅ
String data1 = (String)jsonObj.get("key1");   // hello
String data2 = (String)jsonObj.get("key2");   // world



// ํด๋ผ์˜ success ๋‚ด retData๋กœ ๊ฐˆ ๊ฐ’
JSONObject returnObj = new JSONObject();

// json object์— key : value ์Œ์œผ๋กœ ๊ฐ’์„ ๋„ฃ์–ด ์คŒ
resultObj.put("ret1", "123");
resultObj.put("ret2", "456");

// ์„œ๋ฒ„์—์„œ ํด๋ผ๋กœ ์ „์†ก
out.println(resultObj.toString());

 

๋Œ“๊ธ€