템플리 포멧 형식 변환 코드
String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); };
데이터
- Object {id: 3, writer: Object, contents: "test", createDate: Object, formattedCreateDate: "2017.08.08 10:53:43"}
- contents:"test"
- createDate:Object
- formattedCreateDate:"2017.08.08 10:53:43"
- id:3
- writer:Object
- email:"kiminsu@gmail.com"
- id:1
- name:"김민수"
- password:"1111"
- userId:"admin"
- __proto__:Object
- __proto__:Object
템플릿
<script type="text/template" id="answerTemplate"> <article class="article"> <div class="article-header"> <div class="article-header-thumb"> <img src="https://graph.facebook.com/v2.3/1324855987/picture" class="article-author-thumb" alt=""> </div> <div class="article-header-text"> <a href="#" class="article-author-name">{0}</a> <div class="article-header-time">{1}</div> </div> </div> <div class="article-doc comment-doc"> {2} </div> <div class="article-util"> <ul class="article-util-list"> <li> <a class="link-modify-article" href="/api/qna/updateAnswer/{3}">수정</a> </li> <li> <form class="form-delete" action="/api/questions/{3}/answers/{4}" method="POST"> <input type="hidden" name="answerId" value="{4}"> <button type="submit" class="link-delete-article">삭제</button> </form> </li> </ul> </div> </article> </script>
처리 방법 json 데이터 를 받아오면 변수명.format() 으로 0번 부터 데이터를 넘겨준다.
$(".answer-write input[type=submit]").click(addAnswer); function addAnswer(e){ e.preventDefault(); console.log("click!"); var queryString=$(".answer-write").serialize(); console.log("query : " +queryString); var url =$(".answer-write").attr("action"); console.log("url : " + url); $.ajax({ type:'post', url :url, data: queryString, dataType :'json', error :onError, success:onSuccess }); } function onError(){ console.log("error"); } function onSuccess(data, status){ console.log(data); var answerTemplate =$("#answerTemplate").html(); var template =answerTemplate.format(data.writer.userId, data.formattedCreateDate, data.contents, data.id, data.id); $(".qna-comment-slipp-articles").prepend(template); } String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); };
댓글 ( 4)
댓글 남기기