javascript
jQuery AJAX
코딩하는 둥아
2020. 7. 31. 17:49
728x90
AJAX
전체 페이지의 reloading없이 서버와의 데이터 교환을 통해 웹 페이지의 데이터를 업데이트 할 수 있는 방법
AJAX load() Method
- load()
- $(selector).load(URL, data, callback) ;
- URL : 우리가 로드하고자 하는 url
- data: 우리가 request를 통해 보내고자 하는 key/value 세트
- callback: load() method가 완료된 후 실행될 function
- 특정 selector만 load할 수도 있음
- 아래 예시에서는 h2라는 id를 가진 element만 로드함
$(document).ready(function(){
$('#ajax1').click(function() {
$('#div1').load("ajaxex1.txt");
});
$('#ajax2').click(function() {
$('#div2').load("ajaxex1.txt #h2");
});
});
- callback function
- responseTxt
- call이 성공했을 때 결과로 오는 content
- statusTxt
- call의 상태를 알려줌
- xhr
- XMLHttpRequest object
- responseTxt
$('#ajax1').click(function() {
$('#div1').load("ajaxex1.txt", function(reponse, status, xhr) {
if(status == "success")
alert("External content loaded successfully!");
if(status == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
jQuery - AJAX get() and post() Methods
GET : 특정 리소스에서 데이터를 요청해 받아오는 것
- $.get(URL, callback)
$('#ajax3').click(function() {
$.get("ajaxex2.php", function(data, status){
alert("Data: "+ data + "\nStatus: "+ status);
})
})
해당 버튼을 클릭하면 ajaxex2.php 파일에서 데이터를 받아온다. 받은 데이터가 data에 저장됨!
POST : 특정 리소스에 가공한 데이터를 보내는 것
- $.post(URL, data, callback)
$('#ajax4').click(function() {
$.post("ajax_post.php",
{
name: "SeungA",
city: "Handong"
},
function(data, status){
alert("data: "+data+"\nStatus: "+status);
});
})
// ajax_post.php
<?php
$name = $_POST['name'];
$city = $_POST['city'];
?>
Hello <?= $name ?>, You live in <?= $city ?>!!
728x90