Ajax

Chiho Lee·2021년 10월 11일
0

Ajax Stands for Asynchronous JavaScript And XML

To briefly say, Ajax use XMLHttpRequest Object to correspond with server.

Asyncrhonous? == receive data without reloading pages

Main Features of Ajax

  1. Request to server without reloading.
  2. Get data from server and perform.

Process for Ajax

Ajax란 무엇인가?

1. Make XMLHttpRequest Object.

  • request를 보낼 준비를 브라우저에게 시키는 과정
  • 이것을 위해서 필요한 method를 갖춘 object가 필요함

2. Make callback function.

  • 서버에서 response가 왔을 때 실행시키는 함수

3. Update HTML page

  • Open a request
  • 서버에서 response가 왔을 때 실행시키는 함수
  • HTML 페이지를 업데이트 함

4. send the request


Get 요청 : 특정 페이지 / 자료 읽기
Post 요청 : 서버로 중요 정보 전달

Ajax 쓰는 방법 크게 3가지
  1. jQuery - $.ajax()
  2. axios - axios.get()
  3. javascript - fetch()

Example Code of GET request

<button onClick={()=>{axios.get('URL')}}> 더보기 </button>

.then() - When Ajax request is succeeded
.catch() - When Ajax request is failed

<button onClick={()=>{
  axios.get('URL')}}>
더보기</button>
.then((result)=>{})
.catch(()=>{})

important
in .then(result), result represents all the received data.


Example of POST request

<button onClick={()=>{
  axios.post('서버 URL', {id: 'iamchho', pw:123456})
}}> 더보기 </button>

If you want to get data right after loading component

You have to useEffect()

useEffect(()=>{
  axios.get('서버URL')
  .then()
  .catch()
}. [])

When you add [ ] , functions inside will only run at the first rendering.


profile
Hello,

0개의 댓글