jquery ajax load()
.load() | jQuery API Documentation
Description: Load data from the server and place the returned HTML into the matched elements. Note: Prior to jQuery 3.0, the event handling suite also had a method named .load(). Older versions of jQuery determined which method to fire based on the set of
api.jquery.com
jquery
를 사용하면 XMLHttpRequest
객체를 따로 사용하지 않고 훨씬 간단하게 사용가능하다.
load()
는 가장 간단하게 데이터를 가져오는 방법으로 호출시에 2가지의 인자만 기억하고 있으면 된다.
첫번째는 경로만 잘 적어주어도 데이터를 가져온다.
HTML
<div> </div> <button id="button">Click</button>
JS
$(function() { // 버튼 클릭시 $("#button").click(function(){ $('div').load('sample.txt'); }); });

하지만 2번째 값을 통해서 다양하게 활용가능하다. 해당 파라미터의
response
, status
, xhr
은 XMLHttpRequest
객체의 값들과 비슷한데
jquery
를 통해서 훨씬 간단하게 가져올수 있다.
JS
$(function() { $("#button").click(function(){ /* response : 서버에 요청이 완료되면 결과 내용 status : 서버에 요청을 보내면, 요청의 상태 xhr : 요청한 오브젝트 */ // $('#div').load('경로', 처리 이후에 값 처리 function(reponseTxt, statusTxt, xhr)); $('div').load('sample.txt', function(response, status ,xhr) { console.log(response); console.log(status); console.log(xhr); if(statusTxt == "success" && xhr.status === 200) { console.log('success'); } else { console.log('error'); }; }); }); });

'JavaScript > ajax' 카테고리의 다른 글
js XMLHttpRequest로 데이터 가져오기 (0) | 2021.04.13 |
---|---|
xhr (XMLHttpRequest) (0) | 2021.02.11 |
댓글
이 글 공유하기
다른 글
-
js XMLHttpRequest로 데이터 가져오기
js XMLHttpRequest로 데이터 가져오기
2021.04.13 -
xhr (XMLHttpRequest)
xhr (XMLHttpRequest)
2021.02.11
댓글을 사용할 수 없습니다.