通过 ajax 和 return 变量调用方法 spring mvc 4
calling methods via ajax and return a variable spring mvc 4
我正在学习 spring mvc 4 并且我正在使用 thymeleaf 作为模板引擎...我有一个简单的问题..我有一个要查看的产品列表,用户可以点击例如在点赞按钮上。
据我所知,html 元素通过 href(ajax 或不)调用服务器端控制器,这将使用请求映射调用适当的方法,但是这些方法 returns 表示视图名称的字符串.. 但我不想 return 视图,例如,当用户点击 like 时,我只想调用一个修改 DB 的方法和 return 一个布尔值,如果数据库修改成功,我会更改点赞按钮的颜色;如果失败,我会更改错误消息。我该怎么做?
编辑
这是我想要实现的一个简单示例(只需在产品上单击“赞”按钮时提交 ajax 请求,这样我就可以为用户更新数据库,并且 return 是否插入“赞”入数据库成功与否)
Thymeleaf 模板:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport"
content="width=device-width, initialscale=1, maximum-scale=1.0, user-scalable=no" />
<title>Home</title>
<link rel="stylesheet" type="text/css" media="all"
th:href="@{https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css}"
th:integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
th:crossorigin="anonymous" />
<!-- Optional theme -->
<link rel="stylesheet" type="text/css" media="all"
th:href="@{https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css}"
th:integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
th:crossorigin="anonymous" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<table class="table">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
</tr>
<tr th:each="prod : ${products}">
<td th:text="${prod.id}">Id</td>
<td th:text="${prod.name}">Product Name</td>
<td th:text="${prod.desc}">Product Description</td>
<td>
<div th:id="${prod.id}">
<button id="like-btn">Like</button>
</div>
</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<script
th:src="@{https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js}"></script>
<script th:inline="javascript">
$("#like-btn").click(function() {
var divId = $(this).parent().attr('id');
$.ajax({
type: "GET",
url: ("http://localhost:9090/like?prodId=" + divId),
success: function(){alert("Submit succeeded");},
fail: function(){alert("Submit failed");}
});
});
</script>
</body>
</html>
Spring 控制器:
@Controller
public class HomeController
{
@RequestMapping("/")
public String getHomePage()
{
return "home";
}
@RequestMapping("/products")
public String getProducts(Model model)
{
ArrayList<Product> products = new ArrayList<>();
Product p1 = new Product();
p1.setId(1);
p1.setName("Product 1");
p1.setDesc("Product 1 Description");
products.add(p1);
Product p2 = new Product();
p2.setId(2);
p2.setName("Product 2");
p2.setDesc("Product 2 Description");
products.add(p2);
model.addAttribute("products", products);
return "products";
}
@RequestMapping(value="/like", method=RequestMethod.GET)
public boolean likePage(@RequestParam("prodId") int productId)
{
System.out.println("Prod ID: " + productId);
//DB insert and modification and return result code, just a sample here
//to be processed by jquery
//if(insertionSucceeded)
return true;
//else
// return false;
}
}
但这当然会给出一个错误,指出没有名为 like 的模板。
你可以试试这个代码,
$("#like-btn").click(function(){
var prodLikeId = $(this).parent().attr('id');
$.ajax(function(){
type: "GET",
dataType: "json",
url: "http://localhost:9090/like?prodId="+prodLikeId,
success: function(response){
alert("Submit succeeded"+response);
if(response===true){
window.alert("Update the HTML");
//update the like button color here
$('#like-btn').css('color','blue');
}
},
error: function(e){
alert("Submit failed"+e);
}
});
});
并且在您的控制器中,您需要为 ajax 方法添加 @ResponseBody
注释和 produces = "application/json"
,
@RequestMapping(value="/like", method=RequestMethod.GET,produces = "application/json")
public @ResponseBody Boolean likePage(@RequestParam("prodId") int productId)
{
System.out.println("Prod ID: " + productId);
//DB insert and modification and return result code, just a sample here
//to be processed by jquery
//int res = productService.insertProductLike(productId);
//if(res>0)
return true;
//else
// return false;
}
使用 Firebug 之类的工具来检查 ajax 调用并验证请求-响应数据。或者您也可以使用 Map<String,String>
作为您的方法类型,并通过像 map.put("success","true");
一样填充地图来使用 return 响应。这将 return 一个 json 字符串响应,例如
{"success":"true"}
基于此键值对 json 响应,您可以使用 response.success
在成功块中访问它,并相应地在 HTML.[=18= 中显示或更新数据]
我正在学习 spring mvc 4 并且我正在使用 thymeleaf 作为模板引擎...我有一个简单的问题..我有一个要查看的产品列表,用户可以点击例如在点赞按钮上。
据我所知,html 元素通过 href(ajax 或不)调用服务器端控制器,这将使用请求映射调用适当的方法,但是这些方法 returns 表示视图名称的字符串.. 但我不想 return 视图,例如,当用户点击 like 时,我只想调用一个修改 DB 的方法和 return 一个布尔值,如果数据库修改成功,我会更改点赞按钮的颜色;如果失败,我会更改错误消息。我该怎么做?
编辑 这是我想要实现的一个简单示例(只需在产品上单击“赞”按钮时提交 ajax 请求,这样我就可以为用户更新数据库,并且 return 是否插入“赞”入数据库成功与否)
Thymeleaf 模板:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport"
content="width=device-width, initialscale=1, maximum-scale=1.0, user-scalable=no" />
<title>Home</title>
<link rel="stylesheet" type="text/css" media="all"
th:href="@{https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css}"
th:integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
th:crossorigin="anonymous" />
<!-- Optional theme -->
<link rel="stylesheet" type="text/css" media="all"
th:href="@{https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css}"
th:integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
th:crossorigin="anonymous" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<table class="table">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
</tr>
<tr th:each="prod : ${products}">
<td th:text="${prod.id}">Id</td>
<td th:text="${prod.name}">Product Name</td>
<td th:text="${prod.desc}">Product Description</td>
<td>
<div th:id="${prod.id}">
<button id="like-btn">Like</button>
</div>
</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<script
th:src="@{https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js}"></script>
<script th:inline="javascript">
$("#like-btn").click(function() {
var divId = $(this).parent().attr('id');
$.ajax({
type: "GET",
url: ("http://localhost:9090/like?prodId=" + divId),
success: function(){alert("Submit succeeded");},
fail: function(){alert("Submit failed");}
});
});
</script>
</body>
</html>
Spring 控制器:
@Controller
public class HomeController
{
@RequestMapping("/")
public String getHomePage()
{
return "home";
}
@RequestMapping("/products")
public String getProducts(Model model)
{
ArrayList<Product> products = new ArrayList<>();
Product p1 = new Product();
p1.setId(1);
p1.setName("Product 1");
p1.setDesc("Product 1 Description");
products.add(p1);
Product p2 = new Product();
p2.setId(2);
p2.setName("Product 2");
p2.setDesc("Product 2 Description");
products.add(p2);
model.addAttribute("products", products);
return "products";
}
@RequestMapping(value="/like", method=RequestMethod.GET)
public boolean likePage(@RequestParam("prodId") int productId)
{
System.out.println("Prod ID: " + productId);
//DB insert and modification and return result code, just a sample here
//to be processed by jquery
//if(insertionSucceeded)
return true;
//else
// return false;
}
}
但这当然会给出一个错误,指出没有名为 like 的模板。
你可以试试这个代码,
$("#like-btn").click(function(){
var prodLikeId = $(this).parent().attr('id');
$.ajax(function(){
type: "GET",
dataType: "json",
url: "http://localhost:9090/like?prodId="+prodLikeId,
success: function(response){
alert("Submit succeeded"+response);
if(response===true){
window.alert("Update the HTML");
//update the like button color here
$('#like-btn').css('color','blue');
}
},
error: function(e){
alert("Submit failed"+e);
}
});
});
并且在您的控制器中,您需要为 ajax 方法添加 @ResponseBody
注释和 produces = "application/json"
,
@RequestMapping(value="/like", method=RequestMethod.GET,produces = "application/json")
public @ResponseBody Boolean likePage(@RequestParam("prodId") int productId)
{
System.out.println("Prod ID: " + productId);
//DB insert and modification and return result code, just a sample here
//to be processed by jquery
//int res = productService.insertProductLike(productId);
//if(res>0)
return true;
//else
// return false;
}
使用 Firebug 之类的工具来检查 ajax 调用并验证请求-响应数据。或者您也可以使用 Map<String,String>
作为您的方法类型,并通过像 map.put("success","true");
一样填充地图来使用 return 响应。这将 return 一个 json 字符串响应,例如
{"success":"true"}
基于此键值对 json 响应,您可以使用 response.success
在成功块中访问它,并相应地在 HTML.[=18= 中显示或更新数据]