티스토리 뷰

jQuery/AJAX

jQuery: AJAX

carrot62 2020. 7. 31. 18:04

AJAX비동기적으로, 화면을 새로고침 하지 않아도 서버로부터 데이터를 가져와서 사용하는 방법이다. 
예) 네이버 실시간 검색은 우리가 새로 화면고침하지 않아도 알아서 시간단위로 refresh 된다

  • load() : 서버로부터 데이터를 받아온다

형식:

$(selector).load(URL,data,callback);
  • url: txt, xml 파일처럼 서버로부터 데이터를 받아올 파일. 이 파일은 현재 HTML문서가 위치해 있는 path와 동일한 곳에 있어야 한다!
  • data: 예를 들어서 load("example.php", "#p") 이런식으로 사용하게 되면 내용을 선별해서 가져오는 것이 가능하다

load를 이용해서 데이터를 불러오는 방법

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt");
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

 

자바스크립트를 사용해야 했다면 다음과 같이(아래에 더보기 클릭) 복잡한 코드를 사용해야 했을텐데, jQuery에서 load()를 이용하면 작업이 훨씬 간편해지는 것을 확인 할 수 있다. load를 이용하면 코드 한 줄만으로 txt파일의 내용을 서버로부터 받아올 수 있다.

더보기
<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
  xhttp.send();
}
</script>
 
</body>
</html>

load() callback parameter

function(responseTxt, statusTxt, xhr)
 $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr)

Callback function을 이용해서 파라미터로 받아온 데이터를 가공하는 것이 가능하다. Callfunction 안의 내용은 JSON 방식을 이용해서 작성한다.

$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){	//using callback function
      if(statusTxt == "success")
        alert("External content loaded successfully!");
      if(statusTxt == "error")
        alert("Error: " + xhr.status + ": " + xhr.statusText);
});

Callback function에서의 파라미터는 이미 지정된 변수들이다. 이름은 바꿔도 상관없지만, 위치 별로 각 파라미터의 역할을 가지고 있기 때문에 유의해서 사용하도록 하자!

'jQuery > AJAX' 카테고리의 다른 글

jQuery: GET/POST  (0) 2020.07.31