Day66 :) JQuery AJAX

Nux·2021년 12월 23일
0

자바웹개발

목록 보기
79/105
post-thumbnail

JQuery의 AJAX 처리

  • jQuery의 AJAX는 text, html, xml, json, jsonp의 응답데이터 처리 가능

주요 메서드

$.ajax()

$.ajax([옵션])
  • 비동기식 Ajax를 이용하여 HTTP요청 생성
  • AJAX처리에 필요한 값을 name/value 쌍으로 된 객체로 전달받음
$.ajax({
	// 요청방식
	type: 'Get' or 'Post',
 	// 요청을 보낼 URL
	url: '요청URL',
	// 서버로 보내는 데이터    
	data: {no:14, page:1} or "no=14&page=1",
	// 서버로 보내는 데이터 타입
	// 기본값 "application/x-www-fom-urlendcoded"
	contentType: 'application'/'json'/'text'/'xml', 
	// 응답으로 받을 컨텐츠 타입 지정
	dataType: 'text'/'json'/'xml'/'jsonp',	
	// 응답이 왔을 때 실행되는 함수	
	success: funciton(responseData){},	
	// 서버로 보낸 요청이 실패했을 때 실행되는 함수
	error: function(){} 
})

$.get()

$.get(URL주소[, 데이터], 콜백함수(data[, status][, xhr])[, 응답데이터 타입]);
  • GET 방식의 HTTP 요청을 전송
* URL주소: 요청을 보낼 URL
* 데이터: 요청할 때 서버로 보낼 데이터
* 콜백함수: 성공적인 응답이 왔을 때 실행될 함수
	- data: 서버가 보낸 응답데이터
	- status: 응답처리 상태값
	- xhr: XMLHttpRequest 객체
* dataType: 응답데이터의 컨텐츠 타입을 지정
	- "text": plain text
	- "json": json 형식의 데이터 -> javascript 배열, 객체 변환 후 반환
	- "xml": xml 형식의 데이터 -> XML Document객체로 변환 후 반환
	- "jsonp": 다른 사이트의 서버에 데이터를 요청 시 사용

$.post()

$.post(URL주소[, 데이터], 콜백함수(data[, status][, xhr])[, 응답데이터 타입]);
  • POST 방식의 HTTP 요청 전송

$.getScript()

$.post(URL주소[, 데이터], 콜백함수(data[, status][, xhr])[, 응답데이터 타입]);
  • 서버에서 받은 javaScript 파일을 추가하고 실행시킴

$.getJSON()

$.getJSON(URL주소[, 데이터], 콜백함수(data[, status][, xhr])[, 응답데이터 타입]);
  • GET 방식의 HTTP 요청을 전송하여, 응답으로 JSON 파일을 전송받음

.load()

.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
  • jQuery의 유일한 Ajax 메서드
  • 서버에서 데이터를 읽어 들여 선택자에 HTML코드 배치
// test.txt파일 내에서 id=para인 요소를 읽어와 id=box에 배치
$("#box").load("test.txt #para");

예시

$.get()

$.get("/script2/product/list.hta", function(data){
	$.each(data, funciton(index, product){
		var row = "<tr>"
		row += "<td>"+product.no+"</td>";
		row += "<td>"+product.name+"</td>";
		row += "<td>"+product.company+"</td>";
		row += "</tr>";
		
		$tbody.append(row);
		}
	}

$.ajax

$.ajax({
	type: 'get',
	url: '/script2/product/list.hta',
	dataType: 'json',
	success: function(products){
		var $tbody = $("#table-products tbody");
		$.each(products, function(index, product){
			var row = "<tr>"
				row += "<td>"+product.no+"</td>";
				row += "<td>"+product.name+"</td>";
				row += "<td>"+product.company+"</td>";
				row += "</tr>";
					
				$tbody.append(row);
		})	// each문
	}	// success의 function(products)
});

0개의 댓글