붉은거위 노트 (redgoose note)

[jQuery] 비동기통신이 가능한 $.ajax

Nest
Development
Category
Javascript
Hit
487
Star
0
  • jquery로 다른 파일의 데이터를 가져올 수 있다.
  • 비동기식으로 작동이 가능해서 페이지 새로고침이 필요없이 이벤트만으로 다른 페이지에서의 데이터를 가져올 수 있다.
  • 주로 xml이나 json데이터를 가져오는데 활용된다.
  • post나 get방식을 사용하기 때문에 간편하게 <form/>요소를 사용할 수 있다.
  • 크로스도메인에서 데이터를 로드하는 경우에는 일반적으로 에러가 나지만 dataType: 'jsonp'로 처리해야한다. 이래도 안되면 구글링...
    get방식으로 데이터를 넘겨도 가능하다.

$.ajax 호출부위

기본형은 아니고, 모든 옵션이 다 들어있다.

$.ajax({
    type : 'post' // 전송타입("post", "get")
    ,async : true // true, false
    ,url : 'sample.php' // 처리 url
    ,dataType : 'html' // 전송받을 데이터의 타입("xml", "html", "script", "json"). 미지정시 자동으로 판단
    ,timeout : 30000 // 제한시간 지정(1000 = 1s)
    ,cache : false  // true, false
    ,data : 'apple=1&banana=2' // 서버에 보낼 파라메터. {a:b, c:d} json 형식 입력 가능
    ,contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
    ,error : function(request, status, error)
    {
        // 통신에러 발생시 실행
        console.log('code : ' + request.status + '\r\nmessage : ' + request.reponseText);
    }
    ,success : function(response, status, request)
    {
        // 통신성공
        console.log(response);
    }
    , beforeSend: function() {
        // 통신시작
        console.log('ajax start');
    }
    ,complete: function() {
        // 통신완료
        console.log('ajax complete');
    }
});

기본적으로 들어가는 형태는 아래와 같다.

$.ajax({
    type : 'post'
    ,url : 'sample.php'
    ,dataType : 'html'
    ,timeout : 3000
    ,data : 'apple=1'
    ,error : function(request, status, error)
    {
        console.log('error message');
    }
    ,success : function(response, status, request)
    {
        // 통신성공
        console.log(response);
    }
});

load메서드

  • 굉장히 간단한 방법으로 다른파일의 내용을 가져올 수 있다.
    $('#sample').load('sample.html');

  • 특정 엘리먼트의 내용을 가져올 수 있다. 자세한 내용은 아래 링크를 참고
    참고링크: http://api.jquery.com/load/