티스토리 뷰

■ Ajax
웹 프로그래밍 기술에서 가장 인기있는 기술 중 하나
HTTP scripting을 사용해서 페이지의 refeshes없이 데이타를 로드한다.
jQuery는 강력한 low-level function jQuery.ajax() 으로  
                하나의  high-level utility method 와
                네개의 high-level utility functions 를 정의한다. 



■ The load() Method


모든 jQuery utilities의 가장 간단한 메소드
URL을 비동기로 넘겨서 그 내용물을 가져오고, 그것을 선택된 엘리먼트에 넣거나 대체한다.
// Load and display a status report every 60 seconds
setInterval(function() {
             $("#stats").load("status_report.html");
}, 60000);

가져온 내용물의 일부분만 사용하고 싶으면 다음과 같이 한다.
// Load the temperature section of the weather report
$('#temp').load("weather_report.html #temperature");

load()의  optional arguments
1> data
// Load the weather report for a specified zipcode
$('#temp').load("us_weather.html", "zipcode=02134");
// Here we use an object as data and specify degrees F
$('#temp').load("us_weather.html", { zipcode:02134, units:'F' });
load()ml 는 일반적으로 HTTP GET request를 만들지만, 만약 데이타를 함께 넘긴다면 POST request로 만든다. 
2> callback function
Ajax request가 완료되면 호출된다. 


■ jQuery’s Ajax Status Codes
 

All of jQuery’s Ajax utilities, including the load() method, invoke callback functions to provide asynchronous notification of the success or failure of the request. The second argument to these callbacks is a string with one of the following values:
 
“success”
request 가 성공적으로 수행되었음을 나타냄.
 
“notmodified”
request 는 평사시처럼 완료되었으나 서버가  HTTP 304 “Not Modified” response 보냄
이는 요청한 URL이 이전 요청과 달라지지 않았음을 나타낸다.
이 상태코드는   ifModified option 을 true로 설정했을 때만 나타난다. 

“error”
request  가 성공적으로 완료되지 않았음.
상세한 내용은 XMLHttpRequest object 안에있는  HTTP status code를 확인해야 한다. 

“timeout”
Ajax reques 가 제한된 시간내에 완료되지 못했음을 나타낸다. 
이 상태코드와 함께 error callback이 호출된다. 
기본적으로 jQuery Ajax requests는 time out을 사용하지 않는다. 

“parsererror”
HTTP request 는 성공적으로 완료되었으나  jQuery 가 내용물을 parse하지 못했음을 나타낸다
이 상태코드는 서버가 잘못된 XML document 나 JSON text 를 보낼 때 발생한다. 



■ Ajax Utility Functions
they are invoked directly through jQuery or $, not on a jQuery object.
 
jQuery.getScript()

》첫번째 argument  : JavaScript code 파일의 URL을 첫번째 argument 로 가진다.
It asynchronously loads and then executes that code in the global scope. It can work for both same-origin and cross-origin scripts:
》두번째 argument : callback function 
jQuery will invoke that function once after the code has been loaded and executed 
// Load a library and use it once it loads
jQuery.getScript("js/jquery.my_plugin.js", function() {
       $('div').my_plugin(); // Use the library we loaded
});


jQuery.getJSON()

jQuery.getJSON() 는 callback argumen를 전달할 때만 유용하다. 
If the URL is loaded successfully and its content is parsed successfully as JSON, the resulting object will be passed as the first argument to the callback function.

optional data argument 의 사용
jQuery.getJSON(url, data, callback) 또는 jQuery.getJSON(url, callback) 
데이타가 string이라면 URL에 ? 나 & 형태가 추가되고, 데이타가 object라면 string으로 변환되어 URL에 추가된다.

댓글