๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
JavaScript

[Javascript] XMLHttpRequest ํ†ต์‹ 

by cheezzz 2021. 12. 30.
๋ฐ˜์‘ํ˜•
// XMLHttpRequest ๊ฐ์ฒด ์ƒ์„ฑ
var xmlHttpRequest = new XMLHttpRequest()
  • XMLHttpRequest
    Ajax์™€ ๊ฐ™์ด ๋น„๋™๊ธฐ์ ์œผ๋กœ ์„œ๋ฒ„์™€ ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ๊ณ ๋ฐ›๋Š” ๋ฐฉ์‹์—์„œ ์‚ฌ์šฉํ•˜๋Š” API

    ์ „์ฒด ํŽ˜์ด์ง€์˜ ์ƒˆ๋กœ๊ณ ์นจ ์—†์ด๋„ URL๋กœ๋ถ€ํ„ฐ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์•„์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค


// onreadystatechange ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ์ž‘์„ฑ
xmlHttpRequest.onreadystatechange = function(){
	// ์„œ๋ฒ„์ƒ์— ๋ฌธ์„œ๊ฐ€ ์กด์žฌํ•˜๊ณ  ์š”์ฒญํ•œ ๋ฐ์ดํ„ฐ ์„œ๋ฒ„ ์ฒ˜๋ฆฌ๊ฐ€ ์™„๋ฃŒ๋˜์–ด ์‘๋‹ตํ•  ์ค€๋น„ ์™„๋ฃŒ
	if(xmlHttpRequest.readyState == 4){
		if(xmlHttpRequest.status == 200){
			callbackFunction(0, xmlHttpRequest.responseText);
		}else{
			callbackFunction(xmlHttpRequest.status, xmlHttpRequest.statusText);
		}
	}
};
  • XMLHttpRequest.onreadystatechange
    readystate ์†์„ฑ์ด ๋ณ€๊ฒฝ๋ ๋–„ ํ˜ธ์ถœ ํ•  ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค

  • XMLHttpRequest.readyState
    ์š”์ฒญ์ƒํƒœ๋ฅผ unsigned short๋กœ ๋ณ€ํ™˜
    0: open() ์ „
    1: ๋กœ๋”ฉ ์ค‘
    2: ๋กœ๋”ฉ ์™„๋ฃŒ
    3: ์„œ๋ฒ„ ์ฒ˜๋ฆฌ ์ค‘
    4: ์„œ๋ฒ„ ์ฒ˜๋ฆฌ ์™„๋ฃŒ
  • xmlHttpRequest.status
    ์š”์ฒญ ์‘๋‹ต์ƒํƒœ๋ฅผ ๊ฐ–๋Š” unsigned short๋กœ ๋ณ€ํ™˜
    200: ์„ฑ๊ณต
    403: ์ ‘๊ทผ๊ฑฐ๋ถ€ ์—๋Ÿฌ
    404: ํŒŒ์ผ, ํŽ˜์ด์ง€ ์—†์Œ
    500: ๋ฌธ๋ฒ• ์˜ค๋ฅ˜

  • xmlHttpRequest.responseText
    ์š”์ฒญ์— ๋Œ€ํ•œ ์‘๋‹ต์„ ํ…์ŠคํŠธ๋กœ ๊ฐ–๋Š” DOMString ๋ฐ˜ํ™˜
    ์„œ๋ฒ„์—์„œ ์ „์†กํ•œ ๋ฐ์ดํ„ฐ๋ฅผ text ํ˜•์‹์œผ๋กœ ๋‹ด๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค


xmlHttpRequest.open("POST", url, true);
xmlHttpRequest.setRequestHeader("Content-type", "application/json");
xmlHttpRequest.send( params );
  • xmlHttpRequest.open
    open("์ „์†ก๋ฐฉ์‹", "๊ฒฝ๋กœ", ๋น„๋™๊ธฐ ์‚ฌ์šฉ์—ฌ๋ถ€)

    ๋น„๋™๊ธฐ์‹ ์š”์ฒญ ์ดˆ๊ธฐํ™” ์„ค์ •
    ๋น„๋™๊ธฐ์‹์œผ๋กœ ์š”์ฒญ์„ ๋ณด๋‚ด๋ฉด js๋Š” ์„œ๋ฒ„ ์‘๋‹ต์„ ๊ธฐ๋‹ค๋ฆฌ๋ฉฐ ๋‹ค๋ฅธ ์ผ์„ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค

  • xmlHttpRequest.setRequestHeader
    ์ง€์ •ํ•œ ํ—ค๋”์˜ ํ…์ŠคํŠธ๋ฅผ ๊ฐ–๋Š” ๋ฌธ์ž์—ด ๋ฐ˜ํ™˜
    ์š”์ฒญ ํ—ค๋”์— ๋‚ด์šฉ ์ถ”๊ฐ€(key, value)
    ๋ฐ์ดํ„ฐ ํƒ€์ž… ํ˜•์‹ ์ง€์ •
  • xmlHttpRequest.send
    ์š”์ฒญ ๋ณด๋ƒ„


- ์ „์ฒด์ฝ”๋“œ

var xmlHttpRequest = new XMLHttpRequest()

xmlHttpRequest.open("POST", url, true);
xmlHttpRequest.setRequestHeader("Content-type", "application/json");
xmlHttpRequest.send( params );

xmlHttpRequest.onreadystatechange = function(){
	if(xmlHttpRequest.readyState == 4){
		if(xmlHttpRequest.status == 200){
			callbackFunction(0, xmlHttpRequest.responseText);
		}else{
			callbackFunction(xmlHttpRequest.status, xmlHttpRequest.statusText);
		}
	}
};

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€