http://drst3in.webdoor.co.kr/tc/228
jQuery로 Ajax를 어떻게 쉽게 사용할 수 있는지 보도록 하겠습니다..
jQuery.ajax(settings)
$.ajax(settings)
기본 사용법은 이렇습니다.. 파라미터로 넘어가는 settings 안에서 모든것을 처리하면 됩니다.
settings에 사용되는 속성들을 한번 보겠습니다.
Default: true
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp"
requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
beforeSend(XMLHttpRequest)Function
A pre-callback to modify the XMLHttpRequest object before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument. This is an Ajax Event. You may return false in function to cancel the request.
Default: true, false for dataType 'script' and 'jsonp'
If set to false it will force the pages that you request to not be cached by the browser.
complete(XMLHttpRequest, textStatus)Function
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string categorizing the status of the request ("success"
, "notmodified"
, "error"
,"timeout"
, or "parsererror"
). This is an Ajax Event.
Default: 'application/x-www-form-urlencoded'
When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.
This object will be made the context of all Ajax-related callbacks. For example specifying a DOM element as the context will make that the context for the complete callback of a request, like so:
$.ajax({ url: "test.html", context: document.body, success: function(){
$(this).addClass("done");
}});
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional
setting (described below).
dataFilter(data, type)Function
A function to be used to handle the raw responsed data of XMLHttpRequest.This is a pre-filtering function to sanitize the response.You should return the sanitized data.The function gets passed two arguments: The raw data returned from the server, and the 'dataType' parameter.
Default: Intelligent Guess (xml, json, script, or html)
The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
- "xml": Returns a XML document that can be processed via jQuery.
- "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
- "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
- "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
- "jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.
- "text": A plain text string.
error(XMLHttpRequest, textStatus, errorThrown)Function
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.
Default: true
Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.
Default: false
Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.
Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So{jsonp:'onJsonPLoad'}
would result in 'onJsonPLoad=?'
passed to the server.
jsonpCallbackString
Specify the callback function name for a jsonp request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests.
A password to be used in response to an HTTP access authentication request.
Default: true
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
scriptCharsetString
Only for requests with "jsonp" or "script" dataType and "GET" type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.
success(data, textStatus, XMLHttpRequest)Function
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the 'dataType' parameter; a string describing the status; and the XMLHttpRequest object (available as of jQuery 1.4). This is an Ajax Event.
Set a local timeout (in milliseconds) for the request. This will override the global timeout, if one is set via $.ajaxSetup. For example, you could use this property to give a single request a longer timeout than all other requests that you've set to time out in one second. See$.ajaxSetup() for global timeouts.
Set this to true if you wish to use the traditional style of param serialization.
Default: 'GET'
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Default: The current page
A string containing the URL to which the request is sent.
A username to be used in response to an HTTP access authentication request.
Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.
이것들이 파라미터 안에 사용될수 있는 속성들 입니다... 참 많습니다...
이걸 다 읽기 전에 사용법 보고 나서.. 차근 차근 보셔되 될것 같습니다... 예제 하나 보시죠..
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
이게 Ajax 코드 입니다.. 몇줄 되지도 않습니다... 쉽게 사용할 수 있죠?..
코드를 대충 보면.. $.ajax( 는 jQuery의 ajax함수를 사용하는 거고 {}로 쌓여있는 부분이 파라미터 들입니다.
기본적으로 두개를 사용하고 있습니다...
url : 'ajax/test.html' 이 부분은.. ajax로 호출할 서버의 페이지 주소입니다.. 당연히 무언가를 받아오기 위해서 url를 호출해야 하겠죠...
success : 이부분은 이벤트로.. 서버에서 결과를 정상적으로 받게되면... 이 이벤트가 호출이 됩니다.
이벤트이기 때문에 .. function(data)로 시작하죠... 그럼.. function(data) 에서 data는 서버에서 보내온 정보라 넘어오게 됩니다. 위의 예제에서는.. html 파일을 호출했으니 html 코드가 왔겠군요...
받은 정보를 $('.result') class="result"인 엘리먼트의 innerHtml 로 바꾸는 코드입니다.
그럼.. 이벤트에(사이트에서는. .콜백함수라고 하고있습니다.) 어떤것들이 있는지 한번 보겠습니다.
beforeSend
is called before the request is sent, and is passed the XMLHttpRequest
object as a parameter.
error
is called if the request fails. It is passed the XMLHttpRequest
, a string indicating the error type, and an exception object if applicable.
dataFilter
is called on success. It is passed the returned data and the value ofdataType
, and must return the (possibly altered) data to pass on to success
.
success
is called if the request succeeds. It is passed the returned data, a string containing the success code, and the XMLHttpRequest
object.
complete
is called when the request finishes, whether in failure or success. It is passed the XMLHttpRequest
object, as well as a string containing the success or error code.
5가지의 콜백 함수가 있군요...
beforeSend
는 서버로 요청을 보내기전 호출됩니다.
error
는 호출에 실패하였을때 호출됩니다.
dataFilter
는 ajax를 호출할때 파라미터로 dataType이라는것을 넘겨주게 되는데 이값을 검사하여 호출됩니다.
success
는 서버에서 데이터를 잘 받았을때 호출됩니다.
complate
는 성공이나 실패가나더라도.. 요청이 완료된 상태에서 호출이 됩니다.
dataType
그럼.. dataType이 뭔지 한번 볼까요?...
ajax가 서버로 정보를 요청하고 받을 결과가 어떤 데이터 포멧인지를 지정하는 변수입니다.
기본값을 xml 로 되어 있고 html, json, jsonp, script, text 를 사용할 수 있습니다.
text와 html은 결과 데이터를 그냥 통과시켜 버립니다. 많이 쓰게될 json은 json객체로 결과가 넘어오게 됩니다.
데이터를 배열접근하듯이 쉽게 접근할 수 있습니다.
data
data 속성은 서버로 보낼 post data를 지정하는 속성입니다. 제가 전전장에서 Form 가지고 놀기에서 설명했던 함수를 기억하시는 분이 있겠죠?... 호출하는 url 속성에 get 형식으로 데이터를 넘겨도 되지만.. 많은 데이터를 넘길때는.. data 속성을 사용해서 넣어주면.. post로 넘어가게 됩니다.
post 데이터는 항상 UTF-8로 인코딩 되어서 서버로 전달이 됩니다. data를 넘길때는.. 하나 설정해야 할 속성이 더 있습니다...
contentType 이라는 속성인데 이값을 application/x-www-form-urlencoded로 설정 해주어야 합니다.
기차 자세한 속성들의 정본 사이트를 참조하시면 됩니다...
그럼.. 예제 를 한번 보겠습니다...
$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});
실행할 script 파일을 다운로드 받는 예제입니다.
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
POST 형식으로 데이터를 넘겨서 서버에서 저장하고 메시지를 반환하는 예제입니다.
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
var xmlDocument = [create xml document];
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,
success: handleResponse
});
bodyContent = $.ajax({
url: "script.php",
global: false,
type: "POST",
data: ({id : this.getAttribute('id')}),
dataType: "html",
async:false,
success: function(msg){
alert(msg);
}
}
).responseText;
각 예제들은 사이트에서 확인 가능하며... 속성값들의 설명들을 다시한번 읽어보시기 바랍니다...
===>예제
<script>
function paging(){
count++;
$.ajax({
type: 'post'
, async: true
, url: "/display.do?cmd=productListAppend&ordFlag="+'${ordFlag}'+"&categoryCd="+categoryCd+"&itemCode="+'${itemCode}'+"&count="+count
, beforeSend: function() {
$('#ajax_load_indicator').show().fadeIn('fast');
}
, success: function(data) {
var response = data.trim();
console.log("success forward : "+response);
// 상품 리스트 할당
$('#view_list').append(response);
$('#product_count').html($('#view_list li.thumb').size());
}
, error: function(data, status, err) {
console.log("error forward : "+data);
alert('서버와의 통신이 실패했습니다.');
}
, complete: function() {
$('#ajax_load_indicator').fadeOut();
}
});
}
</script>