1. 단순 구현
ajax.html
<p>이제 <b id="ajax_data"></b>데이터를 가져와라~</p>
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.ajax({
url: "ajax_data.php",
type: "get",
}).done(function(data) {
$('#ajax_data').text(data);
});
</script>
ajax_data.php
<?php
echo 'html, css, js';
?>
2. 서버 통신
ajax.html
<p>어떤 데이터를 가져올까요??</p>
<form>
<input type="text" name="send-1">
<input type="text" name="send-2">
</form>
<button onclick="exec()">실행</button>
<p id="result"></p>
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
function exec() {
$.ajax({
url: "ajax_data.php",
type: "get",
data: $('form').serialize()
}).done(function(data) {
$('#result').text(data);
});
}
</script>
ajax_data.php
<?php
$send_1 = $_GET['send-1'];
$send_2 = $_GET['send-2'];
echo($send_1 . ',' . $send_2);
?>
3. JSON 통신
ajax.html
<p>데이터 가져오기</p>
<p id="result"></p>
<button onclick="next()">가져오기</button>
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
var index = 0;
function next() {
$.ajax({
url: "ajax_data.php",
type: "get",
data: {index: index++}
}).done(function(data) {
data = JSON.parse(data);
$('#result').text(data.word + ' : ' + data.desc);
if(index > 3) index = 0;
});
}
</script>
ajax_data.php
<?php
$index = $_GET['index'];
$word = ['HTML', 'CSS', 'JS', 'JSON'];
$desc = ['Hypertext Markup Language', 'Cascading Style Sheets', 'JavaScript', 'JavaScript Object Notation'];
$json = json_encode(array('word' => $word[$index], 'desc' => $desc[$index]));
echo($json);
?>