최신판 |
당신의 편집 |
3번째 줄: |
3번째 줄: |
| ;$.ajax() | | ;$.ajax() |
| *비동기 HTTP 요청 수행 | | *비동기 HTTP 요청 수행 |
| *jQuery를 통해 보내지는 모든 Ajax 요청의 기본임
| |
|
| |
|
| ==설명==
| | <source lang='jquery'> |
| ;$.ajax(url [, settings])
| |
| *url : 요청될 URL [String 타입]
| |
| *settings : 키/값 형태로 요청과 관련 세부 설정 [PlainObject 타입]
| |
| **data : 서버로 전달될 데이터 [PlainObject / String / Array]
| |
| **dataType : 서버로부터 전달 받기를 원하는 데이터 타입 [xml, html, json, text...]
| |
| **method[type] : 요청할 HTTP 방식 [GET, POST, PUT..]
| |
| **success : 요청이 성공할 경우 호출될 함수 [Function(Aything data, String textStatus, jqHXR jqXHR)]
| |
| | |
| ==$.ajax()==
| |
| *옵션 없이 $.ajax()를 실행하면 단순히 현재 페이지를 불러오며, 그 결과로 아무런 처리를 하지 않음
| |
| <syntaxhighlight lang="javascript">
| |
| $.ajax();
| |
| </syntaxhighlight>
| |
| | |
| ==jqXHR Object==
| |
| *jqXHR은 jQuery XMLHttpRequest Object임
| |
| *$.ajax()에 의해 리턴된 Object임
| |
| *jqXHR은 각 브라우저의 XMLHttpRequest Object를 모두 포함함. (따라서 responseText, responseXML, getResponseHeader()을 기본적으로 모두 포함)
| |
| | |
| ==jqXHR Object 예시==
| |
| * jqXHR은 $.ajax()로 부터 리턴을 받으며 jqXHR은 다양한 메쏘드와 프라퍼티를 함께 가짐. ( Promise interface 참조 )
| |
| * jqXHR의 다양한 메쏘드는 하나 이상의 콜백 함수를 인자로 가지며, $.ajax() 요청이 완료될 때 호출됨
| |
| * 아래 예제의 $.ajax에 의한 요청이 성공적으로 수행되어 jqXHR Object를 돌려 받은 후 done 메쏘드를 실행함. 이때 data는 jqXHR 에서 동일한 형태로 곧장 돌려 받음
| |
| <syntaxhighlight lang="javascript"> | |
| $.ajax({ | | $.ajax({ |
| url: "http://fiddle.jshell.net/favicon.png",
| | url: "test.html", |
| beforeSend: function( xhr ) {
| | context: document.body |
| xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
| | }).done(function() { |
| }
| | $( this ).addClass( "done" ); |
| }).done(function( data ) { | |
| if ( console && console.log ) {
| |
| console.log( "Sample of data:", data.slice( 0, 100 ) );
| |
| }
| |
| }); | | }); |
| </syntaxhighlight> | | </source> |
| | |
| ==예시==
| |
| *예제: http://example.zetawiki.com/jquery/jquery_ajax.html
| |
| *예제에서 불러오는 웹페이지: http://example.zetawiki.com/txt/utf8test.txt
| |
| <syntaxhighlight lang='html5'>
| |
| <script src="//code.jquery.com/jquery.min.js"></script>
| |
| <script>
| |
| $.ajax({
| |
| url: "http://example.zetawiki.com/txt/utf8test.txt",
| |
| }).done(function(data) {
| |
| document.write(data);
| |
| });
| |
| </script>
| |
| </syntaxhighlight>
| |
| | |
| ==$.ajax() 디버깅==
| |
| *ajax() 요청을 통해 프로그래밍을 하다 에러가 발생 할 경우 어떤 이유로 에러가 발생하는지 알 수 없기 때문에 error() 요소를 사용하여 원인을 알아냄
| |
| | |
| <syntaxhighlight lang="javascript">
| |
| $(document).ready(function(){
| |
| $("#fSubmit").click(function(){
| |
| var dataString = {
| |
| id:$("#fId").val(),
| |
| tag:$("#fTag").val(),
| |
| description:$("#fDescription").val(),
| |
| };
| |
| $.ajax({
| |
| url:"{{route('tag.store')}}",
| |
| method:"POST",
| |
| dataType:"json",
| |
| data:dataString,
| |
| success:function(jData) {
| |
| $.each(jData, function(key, val){
| |
| console.log(key);
| |
| console.log(val);
| |
| });
| |
| },
| |
| error:function(request,status,error){
| |
| alert(request.status + "\n" + request.responseText + "\n" + error);
| |
| }
| |
| });
| |
| });
| |
| });
| |
| </syntaxhighlight>
| |
| | |
| ==$.ajax() 사용시 유의할 점==
| |
| *ajax를 통해 form의 값을 전송 할 경우 <input type="submit"....> 형태가 아니나 <button type="button"...> 을 사용하는 것이 좋음. 다시말해 form문이 ajax코드 없이 자체적으로 submit 버튼을 통해 전송 되지 않는지 명확히 한 후 ajax 전송 부분을 구현
| |
| <syntaxhighlight lang="HTML">
| |
| <form id="form_person">
| |
| <input type="text" id="form_name" placeholder="name">
| |
| <input type="text" id="form_age" placeholder="age">
| |
| <button type="button" id="form_submit">Send</button>
| |
| </form>
| |
| </syntaxhighlight>
| |
|
| |
|
| ==같이 보기== | | ==같이 보기== |
| * [[jQuery $.get()]] | | *[[AJAX]] |
| * [[jQuery $.post()]]
| | *[[jQuery 웹페이지 읽기]] |
| * [[jQuery Ajax 이벤트]]
| |
| * [[jQuery 웹페이지 읽기]] | |
| * [[jQuery ajax 스피너 구현]]
| |
| * [[AJAX]]
| |
|
| |
|
| ==참고== | | ==참고 자료== |
| *http://api.jquery.com/jquery.ajax/ | | *http://api.jquery.com/jquery.ajax/ |
|
| |
|
| [[분류: jQuery Ajax]] | | [[분류: jQuery]] |