[jquery] ajax

jQuery 2010. 6. 29. 13:40
사용  

jQuery 의 장점은 코드는 줄이면서 쉽게 사용할 수 있다는 점이다. ajax 역시 jQuery 를 이용하면 코드를 간단하게 사용할 수 있습니다. 

[코드 1. ajax 사용]
$.ajax({
        url: "./ajaxTest.do",
     dataType: "json",    
     success: function(data, textStatus, XMLHttpRequest){
alert("success:"+data+","+textStatus+","+XMLHttpRequest);
        },         
    error:function (x, textStatus, e){ 
alert('ajax Unknow Error.\n'+x.responseText);
        }          
});

dataType  

default 로 jQuery 에서 인식을 하지만 명시적으로 dataType 을 적을 필요가 있습니다.  xml, html, script, json, jsonp, text 등을 dataType 으로 명시할 수 있습니다. 


ajaxSetup  

ajaxSetup 를 이용하여 ajax 에 관련된 공통된 사항들을 셋팅할 수 있습니다. [코드 2]는 error 처리에 관련된 사항들을 ajaxSetup 를 이용하여 셋팅하였습니다. ajax 사용시 ajaxSetup 에 옵션들을 오버라이딩하여 무시할 수도 있습니다. [코드 1] 호출시 error 가 발생하면 [코드 2]의 error 가 아닌 [코드 1]의 error 내용이 호출됩니다. 

[코드 2. ajaxSetup]

$(function(){
$.ajaxSetup({
                 error:function (x, textStatus, e){ 
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('ajaxSetup Unknow Error.\n'+x.responseText);
}
                 }          
    });

기타  

- IE8 에서 ajax cache 문제가 발생하면  $.ajaxSetup({cache: false}); 의 옵션을 이용해 해결할 수 있다고 합니다. 

posted by 소연파파™