- 다운로드하여 웹 브라우저에 보여줌
(2) XMLHttpRequest (XHR)
: 비동기 통신을 위해 서버와 클라이언트 사이에 주고받은 통신 기법
: XMLHttpRequest 객체를 이용하여 사용
2-1) 서버로 자료 요청하기
(1) 객체 생성
new XMLHttpRequest()
let xhr = new XMLHttpRequest()
(2) 요청 초기화
open() 사용
방식 : GET,POST,PUT
자료위치 : 요청할 서버의 url 지정
비동기 여부 : true ) 비동기
false ) 동기
open(방식,자료위치,비동기 여부)
(3) 요청 전송
send() 사용
open()에서 POST로 지정 - 매개변수 ) 서버로 넘길 내용
open()에서 GET로 지정 - null,혹은 빈상태
xhr.open("GET","test.txt",true);
xhr.send(); //get이므로 서버로 넘길 값이 없음
setRequsestHeader(header,value) :
2-2) XMLHttpRequest의 프로퍼티
- readyState
: 객체의 현재 상태를 나타냄 ( 서버로 자료 요청여부, 도착 여부 등)
- status , statusText
: status : http 상태 코드
: statusText : 프로퍼티 상태
- readystatechange 이벤트
: readystate 값이 바뀔 떄 마다 발생하므로 상태에 따라 필요한 명령 처리 가능
— readyState 프로퍼티 값이 4이면서 state 프로퍼티 값이 200일 경우에만 서버에서 제대로 자료를 가져온 상태
- responseText
: 요청에 대한 응답이 문자열 형태로 저장
xhr.responseText
--> 결과
json 내용이 문자열로 저장된 것 확인 가능
(3) JSON 파일 요청
- 사용자 컴퓨터를 서버로 동작 시키려면 node.js 파일 설치 / vs code의 라이버 서버 확장 사용
ex) 서버에 있는 student.json 파일 불러오기
//콘솔 창에서 소스 입력
let xhr = new XMLHttpRequest();
xhr.open("GET","student.json");
xhr.send();
let students = JSON.parse(xhr.responseText);
document.getElementById("result".innerHTML = '${students.name} 학생은
$${students.grade} 학년입니다'
// html의 #result 영역에서 가져온 자료 표시
>> json 자료를 가져와서 화면에 표시하기
ex) 서버에 있는 student.josn 파일 불러오기
- js 파일 만들고 html 문서에 연결
<script src "url"></script>
let xhr = new XMLHttpRequest(); // 서버와 연결하기 위한 객체 생성
xhr.open("GET","student.json");
xhr.send(); // 서버와 연결
xhr.onreadystatechange = function(){
if (xhr.readyState ==4 && xhr.status ==200) { //성공적으로 자료를 가져오면?
let student = JSON.parse(xhr.responseText);
document.getElementById("result").innerHTML = // json 객체로 변환
'<h1>${student.name}</h1>
~~~~~~~~~~~~~ '; //객체의 내용을 화면에 표시
}
}
let xhr = new XMLHttpRequest(); // 서버와 연결하기 위한 객체 생성
xhr.open("GET","student.json");
xhr.send(); // 서버와 연결
xhr.onreadystatechange = function(){
if (xhr.readyState ==4 && xhr.status ==200) { //성공적으로 자료를 가져오면?
let student = JSON.parse(xhr.responseText);
renderHTML(students);
}
function renderHtML(contents){
let output = "";
for (let content of contents){
output +='
<h2>${content.name}</h2>
';
}
document.getElementById("result").innerHTML = output;
}
(4) 예외처리
- 다운로드하여 웹 브라우저에 보여줌
(2) XMLHttpRequest (XHR)
: 비동기 통신을 위해 서버와 클라이언트 사이에 주고받은 통신 기법
: XMLHttpRequest 객체를 이용하여 사용
2-1) 서버로 자료 요청하기
(1) 객체 생성
new XMLHttpRequest()
let xhr = new XMLHttpRequest()
(2) 요청 초기화
open() 사용
방식 : GET,POST,PUT
자료위치 : 요청할 서버의 url 지정
비동기 여부 : true ) 비동기
false ) 동기
open(방식,자료위치,비동기 여부)
(3) 요청 전송
send() 사용
open()에서 POST로 지정 - 매개변수 ) 서버로 넘길 내용
open()에서 GET로 지정 - null,혹은 빈상태
xhr.open("GET","test.txt",true);
xhr.send(); //get이므로 서버로 넘길 값이 없음
setRequsestHeader(header,value) :
2-2) XMLHttpRequest의 프로퍼티
- readyState
: 객체의 현재 상태를 나타냄 ( 서버로 자료 요청여부, 도착 여부 등)
- status , statusText
: status : http 상태 코드
: statusText : 프로퍼티 상태
- readystatechange 이벤트
: readystate 값이 바뀔 떄 마다 발생하므로 상태에 따라 필요한 명령 처리 가능
— readyState 프로퍼티 값이 4이면서 state 프로퍼티 값이 200일 경우에만 서버에서 제대로 자료를 가져온 상태
- responseText
: 요청에 대한 응답이 문자열 형태로 저장
xhr.responseText
--> 결과
json 내용이 문자열로 저장된 것 확인 가능
(3) JSON 파일 요청
- 사용자 컴퓨터를 서버로 동작 시키려면 node.js 파일 설치 / vs code의 라이버 서버 확장 사용
ex) 서버에 있는 student.json 파일 불러오기
//콘솔 창에서 소스 입력
let xhr = new XMLHttpRequest();
xhr.open("GET","student.json");
xhr.send();
let students = JSON.parse(xhr.responseText);
document.getElementById("result".innerHTML = '${students.name} 학생은
$${students.grade} 학년입니다'
// html의 #result 영역에서 가져온 자료 표시
>> json 자료를 가져와서 화면에 표시하기
ex) 서버에 있는 student.josn 파일 불러오기
- js 파일 만들고 html 문서에 연결
<script src "url"></script>
let xhr = new XMLHttpRequest(); // 서버와 연결하기 위한 객체 생성
xhr.open("GET","student.json");
xhr.send(); // 서버와 연결
xhr.onreadystatechange = function(){
if (xhr.readyState ==4 && xhr.status ==200) { //성공적으로 자료를 가져오면?
let student = JSON.parse(xhr.responseText);
document.getElementById("result").innerHTML = // json 객체로 변환
'<h1>${student.name}</h1>
~~~~~~~~~~~~~ '; //객체의 내용을 화면에 표시
}
}
let xhr = new XMLHttpRequest(); // 서버와 연결하기 위한 객체 생성
xhr.open("GET","student.json");
xhr.send(); // 서버와 연결
xhr.onreadystatechange = function(){
if (xhr.readyState ==4 && xhr.status ==200) { //성공적으로 자료를 가져오면?
let student = JSON.parse(xhr.responseText);
renderHTML(students);
}
function renderHtML(contents){
let output = "";
for (let content of contents){
output +='
<h2>${content.name}</h2>
';
}
document.getElementById("result").innerHTML = output;
}