jquery Ajax() 기본 사용법

munilive
Written by munilive on (Updated: )

빠르게 복사해서 사용하기 위해서 jQuery ajax() 메소드의 기본적인 사용 방법과 코드를 정리합니다.

$.ajax({
    type: "post",
    global: true,
    async: true,
    url: "ajax_request.php",
    dataType : "html",
    timeout: 30000,
    cache: true,
    data: {"id":"1", "mode":"write"},
    contentType : "application/x-www-form-urlencoded; charset=utf-8",
    error: function (jqXHR, textStatus, errorThrown) {
        // 통신에 에러가 있을경우 처리할 내용(생략가능)
    },
    success: function (data, textStatus, jqXHR) {
        // 통신이 정상적으로 완료되면 처리할 내용
    },
    beforeSend: function (jqXHR, settings) {
        // 통신이 시작하기전 처리할 내용(생략가능)
    },
    complete: function (jqXHR, settings) {
        // 통신이 완료된 후 처리할 내용 (생략가능)
    }
});
  • type
    • post 또는 get 사용 데이터를 전달할 method 방식을 선택
  • global
    • .ajaxSend(), .ajaxError() 의 전역 이벤트 핸들러를 제어 함, 기본값은 true
  • async
    • 동기, 비동기 방식 설정 기본값은 true, true면 모든 요청은 비동기 방식으로 동작
    • 크로스 도메인과 dataTypejsonp인 경우는 동기방식을 지원하지 않음
    • 동기방식은 요청이 처리될 때까지 브라우저가 일시적으로 잠김
  • url
    • 요청할 파일 주소
  • dataType
    • 요청을 받은 데이터의 타입
    • xml, html, json, jsonp, script, text이 존재 (주로 text, html, json을 많이 씀)
  • timeout
    • 요청 응답 대기 시간 기본적으로 .ajaxSetup()에서 설정한 값을 이용함
    • 지정한 시간 동안 응답이 없으면 error 발생 (대부분 설정하지 않음)
  • cache
    • 기본값 true, 브라우저의 캐시 유무를 설정 false 설정하면 강제적으로 캐싱하지 않음
    • dataTypejsonp, script일 경우에는 false 설정
  • data
    • 요청 시 보낼 데이터
    • .serializeArray() 또는 .serialize()로 전송 가능

참고 사이트

Comments

comments powered by Disqus