본문 바로가기
Backend/JAVA

ajax 공통 모듈

by YERIEL_염주둥 2020. 7. 3.
728x90

크지 않은 폼이라 파일로 빼기 싫어서 모달로 만들어놨더니 비동기 호출해야해서 아주 ajax 남발 ㅋㅋㅋㅋ

 

스크립트가 화면 구성한 code보다 더 많아질꺼 같아서 ajax 공통 모듈을 빼기로 결정


[1] 공통모듈

/**
 * ajax 공통모듈
 * ------------------

 */
var commonAjax = function(url, data, fn, methodType, errormsg){
	// 데이터 값이 잘 넘어왔는지 확인
    console.log(url);
    console.log(data);
    console.log(fn);
    console.log(methodType);
    console.log(errormsg);

  var request = $.ajax({
  url: url,
  method: methodType,
  data: data,
  dataType: "json"
  });

  //콜백함수
  request.done(fn);

  request.fail(function( jqXHR, textStatus ) {
  alert( errormsg + textStatus );
  });
}

함수로 공통모듈 만들기

 

[2] 호출

호출은 함수 호출 해주면 된당!!

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>api test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
	//에러 모달에 문구를 변경하고 싶어서 넣은 문구 코드
    var errormsg ="해당 isbn으로 도서 정보를 불러올수 없습니다."
    
    //ajax가 정상 호출 되었을때 실행 되는 함수
    var fn = function( data ) {
    	console.log(JSON.stringify(data) + " <- ajax");
    }
    
    //공통모듈 ajax 함수 호출하기
    commonAjax("/searchIsbn", 
    { data : //값 },
    fn,
    'get',
    errormsg);
});
</script>
</head>
</html>

 

 

길어 보이지만 원래 부르는 것과 비교해보면 그래도 깔끔깔끔 ㅋㅋㅋ

 


jquery ajax 작성

https://r-0o0-j.tistory.com/71?category=845043

 

jQurey - Ajax

도대체 Ajax이 뭔대 콘텐츠 타입을 먼저 다루는가? 1) text/html - html를 표현하는 타입 2) text/xml - xml를 표현하는 타입 (외부 자원 관리 데이터로 저장 혹은 통신하기 위한 파일) 3) text/plain - 텍스트를.

r-0o0-j.tistory.com

 

json 방식

https://r-0o0-j.tistory.com/70?category=845043

 

jQuery - json Ajax

1. 화면 만들기 <%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%> {"name":"홍길동","age":25, "array" : ["전주","익산"]} json의 데이터 타입은 application/js..

r-0o0-j.tistory.com

 

html 방식

https://r-0o0-j.tistory.com/69?category=845043

 

jQuery - Html Ajax

1. 호출 버튼을 눌렀을때 연결된 주소(ajaxHtmlCall.jsp)의 내용이 가져와지는 확인하기 ajax - html 호출 호출 버튼을 클릭해주세요. 2. html 내용 채우기 <%@ page language="java" contentTyp..

r-0o0-j.tistory.com

 

반응형

'Backend > JAVA' 카테고리의 다른 글

객체지향 설계 5대 원칙 - SOILD 원칙  (1) 2020.07.01
JAVA - Generic  (0) 2020.05.22
JAVA 예외 던지기 Throw  (0) 2020.05.20
JAVA 예외처리하기 RuntimeException  (0) 2020.05.20
MVC Servlet - controller 작성하기 - Filter  (0) 2020.05.14

댓글