TIP게시판

제목 제가 연구한 ajax json관련 소스인데 별로 안좋을 수 있지만 공개합니다.
글쓴이 작성시각 2016/01/13 16:58:48
댓글 : 6 추천 : 0 스크랩 : 1 조회수 : 13818   RSS
function alert_msg (msg) {
	//alert(msg);
	$(".design_alert .msg").html(msg.replace(/\n/g, "<br />"));
	//$(".design_alert").fadeIn().delay(3000).fadeOut();
	$(".design_alert").show(0).delay(3000).hide(0);
}
​
var ajaxJsonBool = true; //ajax가 실행되는지,
var ajaxJsonDelay = 50; //ajax가 실행중이면 재 요청할 시간
/**
 * ajax json
 * @param action string url
 * @param data array 
 * @param $el 엘리먼트 (jquery element obj)
 * @param successFn success callback
 * @param loading 엘리먼트 (jquery element obj)
 * @param errorFn error callback
 * @param timeout micro second
 * 
 */
function ajaxJson (action,data,$el,successFn,loading,errorFn,timeout) {
	if(ajaxJsonBool){
		if ( loading !== undefined ) {
			if ( loading == 1 ) {
				$(".loading").show();
			} else {
				loading.show();
			}
		}
		ajaxJsonBool = false;
		
		var ajaxTimeOut = 5000;
		if ( timeout !== undefined ) {
			ajaxTimeOut = timeout;
		}
		
		var setting = {
			    url : action,
			    type : 'post',
			    timeout : ajaxTimeOut,
			    dataType : 'json',
			    data : data,
			    success : function(returnData){
			    	if ( loading !== undefined ) {
						if ( loading == 1 ) {
							$(".loading").fadeOut();
						} else {
							loading.fadeOut();
						}
					}
			    	//만약 메세지가 정의되었으면..
			    	if ( returnData.msg !== undefined ) {
			    		//alert(returnData.msg);
			    		alert_msg(returnData.msg);
			    	}
			    	
			    	//만약 리턴된 html이 정의되었으면..
			    	if ( returnData.returnHtml !== undefined ) {
			    		$el.html(returnData.returnHtml);
			    	}
			    	
			    	//만약 타입이 함수면...
			    	if ( typeof ( successFn ) == "function" ){
			    		successFn(returnData);
			    	}
			    	setTimeout(function(){ajaxJsonBool = true;},ajaxJsonDelay);
			    },
			    error : function(jqXHR, textStatus, errorThrown){
			    	if ( loading !== undefined ) {
						if ( loading == 1 ) {
							$(".loading").fadeOut();
						} else {
							loading.fadeOut();
						}
					}
			    	if ( typeof ( errorFn ) == "function" ){
			    		errorFn(jqXHR, textStatus, errorThrown);
			    	} else {			        
				        alert_msg( ajaxJsonError(jqXHR, textStatus, errorThrown) );
			    	}
			    	
			        ajaxJsonBool = true;
			    }
			};
		/*
		if ( addSetJson !== undefined ) {
			var obj = jQuery.parseJSON(addSetJson);
			
			for (var i in obj) {
				eval("setting." + i + " = " + obj[i] + ";");
			}
		}
		*/
		
		$.ajax(setting);
		
	}else{
		setTimeout(function(){ ajaxJson (action,data,$el,successFn,loading,errorFn,timeout); },ajaxJsonDelay);
	}
}

function ajaxJsonError(jqXHR, textStatus, errorThrown) {
	var err_msg = '';
    if (jqXHR.status === 0) {
    	err_msg = '네트워크가 오프라인입니다.\n네트워크를확인하시기 바랍니다.';
    } else if (jqXHR.status == 404) {
    	err_msg = '요청 된 페이지를 찾을 수 없습니다. [404]';
    } else if (jqXHR.status == 500) {
    	err_msg = '내부 서버 오류. [500]';
    } else if (textStatus === 'parsererror') {
    	err_msg = '요청 된 JSON 구문 분석에 실패했습니다.';
    } else if (textStatus === 'timeout') {
    	err_msg = '시간 초과 오류가 발생했습니다.';
    } else if (textStatus === 'abort') {
    	err_msg = 'Ajax 요청이 중단되었습니다.';
    } else {
    	err_msg = 'Uncaught Error.\n' + jqXHR.responseText;
    }
    return err_msg;
}

 

//실 사용 코드
function priceBatchSubmit (no) {
    	var f = $("form.priceBatch");
		var action = f.attr('action');
		var action = '/' + mgf + '/air/comUpdate';
		
		var data = new Array();
		data = f.serializeArray();
		data.push({ name: csrf_name, value: csrf_hash });
		
		ajaxJson(action,data,undefined,function(){
			createPromotionCal(no);
		},$("dl.calControl .loading2"));
    }

 

 

//php 코드

//객실 가격 달력폼
	function roomInfoPriceForm ($roomNo) {
		$this->layout = 'default';
		
		//아작스 호출인지
		if ( $this->input->is_ajax_request() ) {
			$returnHtml = $this->stay_model->roomInfoPriceFormCal( $roomNo, $this->input->post("y"), $this->input->post("m") );
			json_alert( array( 'returnHtml' => $returnHtml ) );
		} else {
			alert('잘못된 접근입니다.');
		}
	}


// ajax json echo and exit
function json_alert($msg='') {
	echo json_encode($msg);
	exit;
}


 

//응용...

/객실 달력 서브밋
	function roomCalSubmit() {
		$this->layout = 'default';
		
		//아작스 호출인지
		if ( $this->input->is_ajax_request() ) {
			$this->load->library('form_validation');
				
			$config = array(
					array('field'=>'dPrice[]', 'label'=>'판매가', 'rules'=>'trim|xss_clean'),
					array('field'=>'rPrice[]', 'label'=>'입금가', 'rules'=>'trim|xss_clean'),
					array('field'=>'year', 'label'=>'연', 'rules'=>'required|trim|xss_clean'),
					array('field'=>'month', 'label'=>'월', 'rules'=>'required|trim|xss_clean'),
					array('field'=>'rm_no', 'label'=>'prkey', 'rules'=>'required|trim|xss_clean|is_natural'),
			);
				
			$this->form_validation->set_rules($config);
			
			//폼검증.
			if ($this->form_validation->run() == FALSE) {
				
				if( validation_errors() ){
					json_alert( array( 'stat' => 0, 'msg' => strip_tags(validation_errors()) ) );
				}
				
			} else {
				$no = $this->input->post('rm_no');
				$year = $this->input->post('year');
				$month = $this->input->post('month');
				
				//공유데이터면서 공유업체가가 아니면..
				if ( ! $this->sc_cm_no && $this->tmp_ta_cm_no != 'share' ) {
					//
				} else {
					$this->stay_model->roomCalSubmit();
				}
				
				json_alert(array( 'stat' => 2, 'msg'=>'등록되었습니다.','no' => $no,'year' => $year,'month' => $month ));
			}
				
		} else {
			alert('잘못된 접근입니다.');
		}
	}

 

 다음글 푸시불렛 푸시 발송 (14)
 이전글 php 7.0.1 업데이트 (centos6, yum) (15)

댓글

한대승(불의회상) / 2016/01/13 17:43:50 / 추천 0

좋은 정보 감사 합니다. ^^

/ 2016/01/13 18:15:18 / 추천 0

//불의회상

올려놓고 보니 장황하네요.

제 프로젝트에 쓸라고 만들었는데, 도움이 될까하고 올렸습니다.

kaido / 2016/01/14 09:26:44 / 추천 0

좋은 정보 감사 합니다.

여기에 프로미스 패턴까지 들어가 있으면 금상 첨화가 될것 같습니다.

/ 2016/01/14 12:39:24 / 추천 0

//kaido

그렇군요.. 문제가 있다곤 생각했는데, 힌트를 얻었습니다.

공부좀 해서 또 올릴게요 ..

kaido / 2016/01/14 14:00:08 / 추천 0

@닉

아니요 ㅎㅎ

프로미스 패턴 까지 요구되는 경우는 드문 케이스 입니다.

다만 언젠가 한번 요구를 해오는 경우가 있어요.

/ 2016/01/27 17:57:33 / 추천 0

@kaido

 

/**
 * ajax json
 * @param action string url
 * @param data array 
 * @param $el 엘리먼트 (jquery element obj)
 * @param successFn success callback
 * @param loading 엘리먼트 (jquery element obj)
 * @param errorFn error callback
 * @param timeout micro second
 * 
 */
function ajaxJson (action,data,$el,successFn,loading,errorFn,timeout) {
 if ( loading !== undefined ) {
  if ( loading == 1 ) {
   $(".loading").show();
  } else {
   loading.show();
  }
 }
 
 var ajaxTimeOut = 5000;
 if ( timeout !== undefined ) {
  ajaxTimeOut = timeout;
 }
 
 var setting = {
     url : action,
     type : 'post',
     async: false,
     timeout : ajaxTimeOut,
     dataType : 'json',
     data : data,
     success : function(returnData){
      if ( loading !== undefined ) {
    if ( loading == 1 ) {
     $(".loading").fadeOut();
    } else {
     loading.fadeOut();
    }
   }
      //만약 메세지가 정의되었으면..
      if ( returnData.msg !== undefined ) {
       //alert(returnData.msg);
       alert_msg(returnData.msg);
      }
      
      //만약 리턴된 html이 정의되었으면..
      if ( returnData.returnHtml !== undefined ) {
       $el.html(returnData.returnHtml);
      }
      
      //만약 타입이 함수면...
      if ( typeof ( successFn ) == "function" ){
       successFn(returnData);
      }
     },
     error : function(jqXHR, textStatus, errorThrown){
      if ( loading !== undefined ) {
    if ( loading == 1 ) {
     $(".loading").fadeOut();
    } else {
     loading.fadeOut();
    }
   }
      if ( typeof ( errorFn ) == "function" ){
       errorFn(jqXHR, textStatus, errorThrown);
      } else {           
          alert_msg( ajaxJsonError(jqXHR, textStatus, errorThrown) );
      }
     }
 };
 
 return $.ajax(setting);
}

 //이름등 저장
 function reservBasicForm () {
  var action = '/reserv/reservBasicForm';
  
  var data = new Array();
  data.push({ name: csrf_name, value: csrf_hash });
  
  var basic = ajaxJson(action,data,undefined,function(doc){
   alert(1);
  });
  
  return basic;
 };
  
 //항공저장
 function reservAirForm (f,allBt) {
  var action = '/reserv/reservAirForm';
  
  var data = new Array();
  data = f.serializeArray();
  data.push({ name: csrf_name, value: csrf_hash });
  
  var air = ajaxJson(action,data,undefined,function(data){
   alert(2);
  });
  
  return air;
 };
 
 //숙소저장
 function reservStayForm (f,allBt) {
  var action = '/reserv/reservStayForm';
  
  var data = new Array();
  data = f.serializeArray();
  data.push({ name: csrf_name, value: csrf_hash });
  
  var stay = ajaxJson(action,data,undefined,function(data){
   alert(3)
  });
  
  return stay;
 };
 
 //모두저장
 $('.rsv_sv').click(function(){
  var XHRs = [];
  XHRs.push(reservBasicForm());
  
  $(".reservAirForm").each(function(i,el){
   XHRs.push(reservAirForm($(el)));
  });
  
  $(".reservStayForm").each(function(i,el){
   XHRs.push(reservStayForm($(el)));
  });
  
  $.when.apply(undefined, XHRs).then(function () {
   alert(4);
  },function(){
   alert('실패');
  });
  return false;
 });

 

바뀐점...

settimeout 대신 async: false, 옵션 추가.

마지막에 retrun문이 들어갑니다..

async: false, << 은 동기로 실행되게 하는 옵션...