Jiang Zerui 极简-Live a little

前后分离的站点重写04

自用方式

$(function () { $(“.btn”).click(function () { var name = $(“#name”).val(); var email = $(“#email”).val(); var message = $(‘#message’).val(); var articleId = $(‘#articleId’).text(); var comment = { name: name, email: email, content: message, article_id:articleId, }

   $.ajax({
		url: 'http://localhost:2812/api/save/comment',
		type: "post",
		dataType: "json",
		data: {
			comment: JSON.stringify(comment)
		},
		success: function(data) {
			
		}
   });
});   });

对应Controller @PostMapping(“save/comment”) public String addMessage( HttpServletRequest request) { String ip = request.getRemoteAddr(); Comment comment = new Comment(); comment.setIp(ip); String json = request.getParameter(“comment”); JSONObject jsonObject = new JSONObject().parseObject(json); comment.setArticle_id((Integer) jsonObject.get(“article_id”)); comment.setEmail(jsonObject.get(“email”).toString()); comment.setName(jsonObject.get(“name”).toString()); commentService.addComment(comment); return null; }

以下文章救了我

一、传递简单json字符串

前台

var sendDatas = { userName : ‘张三’, userPassword : ‘123456’ };

$.ajax({

type : “post”,

url : “testjson”,

dataType : “json”,

//注意:这里不能加下面这行,否则数据会传不到后台

// contentType: “application/json;charset=utf-8”,

data : sendDatas,

success : function(data) {

} });

后台

@RequestMapping(value=”testjson”,method=RequestMethod.POST)

@ResponseBody

public Object testjson(String userName,String userPassword) {

System.out.println(userName); return “test”;

}

二、传递数组类型json(传JSON字符串+@RequestBody接收)

前台

var sendDatas1 =

{ list : [ { test1 : ‘张三1’, test2 : ‘123’ }, { test3 : ‘张三2’, test4 : ‘123’ }, { test5 : ‘张三3’, test6 : ‘123’ }, { test7 : ‘张三4’, test8 : ‘123’ }

] }; $.ajax({
type : "post",
url : "testjson1",
dataType : "json",
contentType : "application/json;charset=utf-8",//关键是要加上这行
traditional : true,//这使json格式的字符不会被转码
data : JSON.stringify(sendDatas1),
success : function(data) {
} });

后台

@PostMapping(value=”testjson1”)

@ResponseBody

public Object testjson1(@RequestBody Object lArray ) {

System.out.println(lArray); return “test”;

}