개발/PHP
ajax - json을 이용한 아작스 간단예제
똘또히
2017. 8. 16. 19:01
$.ajax(settings)
- jQuery를 이용한 ajax통신의 가장 기본적인 API
- 주요속성
- data : 서버에 전송할 데이터, key/value 형식의 객체
- dataType : 서버가 리턴하는 데이터 타입 (xml, json, script, html)
- type : 서버로 전송하는 데이터의 타입 (POST, GET)
- url : 데이터를 전송할 URL
- success : ajax통신에 성공했을 때 호출될 이벤트 핸들러
예제1-1. 웹페이지
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!DOCTYPE html> < html > < head > </ head > < body > < div id = "result" ></ div > < input type = "text" id = "msg" /> < input type = "button" value = "get result" id = "getResult" /> < script > $('#getResult').click( function() { $('#result').html(''); $.ajax({ dataType:'json', type:'POST', data:{'msg':$('#msg').val()}, success:function(result){ if(result['result']==true){ $('#result').html(result['msg']); } } }); }) </ script > </ body > </ html > |
예제 1-2. 서버 쪽 로직
1 2 3 | <? echo json_encode(array('result'=>true, 'msg'=>$_REQUEST['msg'])); ?> |
본 자료는 https://opentutorials.org/course/53/49 에서 퍼온 자료입니다.