C와 View 간에 데이터를 통신하는 방법

php中世界最好的语言
풀어 주다: 2018-04-02 13:46:44
원래의
1314명이 탐색했습니다.

이번에는 C와 View 사이의 데이터 교환 방법에 대해 설명하겠습니다. C와 View 사이의 데이터 교환에 대한 주의 사항은 무엇입니까?

jQuery.post(url, [data], [callback], [type])

url,[data],[callback],[type]String,Map,Function,StringV1.0url: 요청 주소를 보냅니다.

data: 전송할 키/값 매개변수입니다.

콜백: 콜백 기능 전송이 성공했을 때.

유형: 컨텐츠 형식, xml, html, 스크립트, json, 텍스트, _default를 반환합니다.

적용 형식:

$.post("test.php", function(data){
  alert("Data Loaded: " + data);
 });
$.get("comment/getComments?parentId="+parentId+"&topicId="+topicId,function(data){
 var appendButton ="";
 var append = "";
 if(data!=""){
  var arr = data.split("$");
  var allTr="";
  for(var i = 0;i<arr.length;i++){
  var arr2 = arr[i].split(&#39;,&#39;);
  var name = arr2[3];
  var content = arr2[0];
  var time= "/Date("+arr2[1]+")/";
  time = DateFormat(time);
  var id = arr2[2];
  var table = "<table><tr><td>"+content+"</td></tr><tr><td>"+time+"</td></tr></table>";
  appendButton = appendButton+table+"<button type = &#39;button&#39; id = &#39;toAddCommentId&#39; onclick = &#39;replaceFrom("+parentId+",\""+name+"\""+")&#39;>回复</button>";
  }
  appendButton = appendButton+"<button type = &#39;button&#39; onclick = &#39;replaceFrom("+parentId+","+"\""+userName+"\""+")&#39;>我也说一句</button>";
 }
 appendButton = appendButton+"<p id = &#39;commentButton&#39; ></p><p id = &#39;textareaId&#39;></p>";
 if(data==""){
  appendButton = appendButton+"<textarea id=&#39;textareaId"+parentId+"&#39; rows=&#39;2&#39; cols=&#39;77&#39; validate=&#39;required&#39; validate-message=&#39;不能为空!&#39; name = &#39;content&#39; >@"+userName+"...."+"...."+parentId+":</textarea><button type = &#39;button&#39; id = &#39;commentContentId&#39; onclick = &#39;submit("+topicId+","+parentId+","+"\""+userName+"\""+")&#39;>发表</button>";
 }
 $("#addCommentId"+parentId).html(appendButton);
 });
로그인 후 복사

백엔드:

@RequestMapping(value = "/saveAndGetComments", params = {"topicId","parentId"}, method = RequestMethod.POST)
 @ResponseBody
 public String saveAndGetComments(long topicId,Comment comment,long parentId) throws UnsupportedEncodingException{
 comment.setParentId(parentId);
 commentService.save(comment,topicId);
 List<Comment> comments=commentService.listByCommentId(parentId);
 return append(comments);
 }
 
 private String append(List<Comment> comments) {
 StringBuffer sb=new StringBuffer();
 for(int i=0;i<comments.size();i++){
  Comment comment = comments.get(i);
  sb.append(comment.getContent());
  sb.append(",");
  sb.append(comment.getCreateTime().getTime());
  sb.append(",");
  sb.append(comment.getId());
  sb.append(",");
  sb.append(comment.getUser().getName());
  if(i!=comments.size()-1){
  sb.append("$");
  }
 }
 return sb.toString();
 }
로그인 후 복사

Note, springmvc3 주석 @responseBody를 사용하여 매개변수를 전달하세요.

자주 사용하는 js 함수:

위 데이터는 json을 이용해 전송되는데, js가 json으로 전달된 날짜를 파싱할 때, 이때는 우리가 원하는 형식이 아닙니다.

먼저 과거 날짜를 전달하고 이를 시간으로 설정합니다. date.getTime()

에 전달한 다음 js에서 작동합니다.

var date= "/Date("+time+")/";
date = DateFormat(date);
/**
 * 处理时间
 * @param value
 * @returns {String}
 */
function DateFormat(value) {
  var date = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
  var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
  var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var Hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  var Minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var Seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return date.getFullYear() + "/" + month + "/" + currentDate + " " + Hours + ":" + Minutes + ":" + Seconds;
}
로그인 후 복사
이 기사의 사례를 읽은 후 방법을 마스터했다고 믿습니다. . 더 흥미로운 정보를 보려면 다른 PHP 중국어 웹사이트 관련 기사를 주목하세요!

추천 자료:

Ajax 상호 작용 중에 보고된 status=parsererror 오류를 해결하는 방법

Ajax에서 like 기능을 직접 구현하는 단계별 설명

위 내용은 C와 View 간에 데이터를 통신하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!