크로스도메인(Cross Domain) 처리( jQuery & JSONP 사용 )
var HTTP_STATUS_CODE = {
//HTTP 1.1 status codes
100 : 'Continue',
101 : 'Switching protocols',
200 : '전송 성공',//'OK, 에러없이 전송 성공',
201 : 'Created, POST 명령 실행 및 성공',
202 : 'Accepted, 서버가 클라이언트 명령을 받음',
203 : 'Non-authoritative information, 서버가 클라이언트 요구 중 일부 만 전송',
204 : 'No content, 클라언트 요구을 처리했으나 전송할 데이터가 없음',
205 : 'Reset content',
206 : 'Partial content',
300 : 'Multiple choices, 최근에 옮겨진 데이터를 요청',
301 : 'Moved permanently, 요구한 데이터를 변경된 임시 URL에서 찾았음',
302 : 'Moved temporarily, 요구한 데이터가 변경된 URL에 있음을 명시',
303 : 'See other, 요구한 데이터를 변경하지 않았기 때문에 문제가 있음',
304 : 'Not modified',
305 : 'Use proxy',
400 : 'Bad request, 클라이언트의 잘못된 요청으로 처리할 수 없음',
401 : 'Unauthorized, 클라이언트의 인증 실패',
402 : 'Payment required, 예약됨',
403 : 'Forbidden, 접근이 거부된 문서를 요청함',
404 : 'Not found, 문서를 찾을 수 없음',
405 : 'Method not allowed, 리소스를 허용안함',
406 : 'Not acceptable, 허용할 수 없음',
407 : 'Proxy authentication required, 프록시 인증 필요',
408 : 'Request timeout, 요청시간이 지남',
409 : 'Conflict',
410 : 'Gone, 영구적으로 사용할 수 없음',
411 : 'Length required',
412 : 'Precondition failed, 전체조건 실패',
413 : 'Request entity too large,',
414 : 'Request-URI too long, URL이 너무 김',
415 : 'Unsupported media type',
500 : 'Internal server error, 내부서버 오류(잘못된 스크립트 실행시)',
501 : 'Not implemented, 클라이언트에서 서버가 수행할 수 없는 행동을 요구함',
502 : 'Bad gateway, 서버의 과부하 상태',
503 : 'Service unavailable, 외부 서비스가 죽었거나 현재 멈춤 상태',
504 : 'Gateway timeout',
505 : 'HTTP version not supported '
};
===========================================================================
함수제작 (이영수)
:: 사용자정의함수를 호출하게되면 호출된 오브젝트를 기존 오브젝트에서 오버라이드 한다.
:: AJAX를 통해 JSONP를 이용하는경우 기본적으로는 아래 사항을 준수해주길 권한다.
1. 상세설명 :
1. 통신방법(GET방식 기준으로 설명)
- 클라이언트에서 요청시 :
http:// 도메인 / ....?
? 는 jQuery가 인코딩시 자동으로 jQuery423423423_423432 형태로 자동으로 생성되어 callback변수에 값이 들어가게된다.
직접지정도 가능함 (예 : http:// 도메인 / ....?callback=콜백함수명)
- 서버에서 응답시 :
echo $_GET['callback'].'('.json_encode(변수).');' ;
2. 통신방법(GET방식 기준으로 설명)
- 클라이언트에서 요청시 :
$.ajax함수를 이용하는 경우 함수에 추가내용
url : 'http:// 도메인 / ....',
type : 'GET', // POST 사용시 contentType를 교체바람(사용하는 경우 403에러뜸;접근거부) --> (X) contentType: "application/jsonp; charset=utf-8"
dataType : 'jsonp',
jsonpCallback: "response_callback", // 콜백 : 사용자정의함수(response_callback) 존재하든 존재하지않든 사용가능
contentType: "application/jsonp; charset=utf-8" // JSONP 인 경우
- 서버에서 응답시 :
echo $_GET['callback'].'('.json_encode(변수).');' ;
2. 처리방식
--> 메서드 : GET 방식
--> contentType : application/json; charset=utf-8
===========================================================================
var Request_ajax = function(opts){ // ajax 사용자 함수
if("object" !== typeof opts) opts = {}; // arguments인 opts변수값이 없을경우
$.ajax( $.extend(true, { // 오버라이드(Override)
url : '',
type : 'GET', // GET, POST
dataType : '', // html, xml, json, jsonp, text, script
cache : false,
aysnc : false, // true(비동기), false(비동기)
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
data : '', //?? .serialize()
error : function(jqXHR, textStatus, errorThrown){
//res = textStatus+' :['+jqXHR.status+'] '+errorThrown+' ' ;
console.log('on error!',jqXHR,textStatus, errorThrown);
},
/*
jsonp : '',
jsonpCallback: '', // 서버로부터 되돌려받을 콜백함수
success: function(response){}
contentType: 'multipart/form-data'
contentType: 'application/x-www-form-urlencoded'
contentType: 'application/x-www-form-urlencoded; charset=UTF=8'
contentType: 'application/json; charset=utf-8'
beforSend : function(xhr, settings){},
*/
complete: function(e, xhr, settings){
/*
e.readyState
*
*
0 : 객체가 생성됬지만 초기화 되지 않은상태
1 : 객체가 생성됬지만 send메서드가 호출되지 않음
2 : 로딩중 (send메서드는 호출되었지만 상태와 헤더는 아직 사용불가)
3 : 일부 데이터들을 수신중. 상태와 응답 헤더가 아직 완전히 사용가능하지는 않음
4 : 모든 데이터가 수신됬으며 rseponseBody와 responseText 속성들을 통해 완전한 데이터를 얻을 수 있다
*
*
xhr
*
xhr.responseHTML
xhr.responseXML
xhr.responseJSON
settings.url
e.responseJSON // 응답받은 JSON데이타
*/
if(e.status === 200){
console.log('default result: ', e);
if($.isFunction(this.complete_add)){
this.complete_add();
}
if( this.dataType == 'jsonp' ) {
//console.log(e.responseJSON._GET.callback);
if(e.responseText) {
(function() { eval(e.responseText);})(); }
}
}else{
alert(HTTP_STATUS_CODE[e.status]) ;
return ;
}
}
}, opts));
}
===========================================================================
사용 예
===========================================================================
Request_ajax({
url : '/admin/menu/main',
type : 'POST',
//contentType: "application/jsonp; charset=utf-8",
dataType : 'jsonp',
jsonpCallback: "beforSend_callback",
data : ued_encode({
"property" : "create_node",
"id" : data.rslt.parent.attr("id").replace("mnu_",""),
"position" : data.rslt.position,
"title" : data.rslt.name,
"type" : data.rslt.obj.attr("rel")
}),
complete: function(e, xhr, settings){
if(e.status === 200){
if($.isFunction(this.complete_add)){ // 사용자 정의함수 :: ① 참고바람
this.complete_add();
}
if( this.dataType == 'jsonp' ) {
console.log(e.responseText);
console.log('sssd',e.responseJSON);
if(e.responseText) {
(function() { eval(e.responseText);})(); } // 서버로부터 콜백받은 함수 실행
}
}else{
alert(HTTP_STATUS_CODE[e.status]) ;
return ;
}
},
complete_add : function(){ // ①
// 요청하고 응답이 왔을때 추가로 여기에 처리문을 넣게되면 실행된다 위의 ①를 참고바람
sos();
}
});