这是我的控制器:@Controller
@RequestMapping("/test")
public class TestServlet {
@RequestMapping("/country/{latitude}-{longitude}")
public String getCountry(@PathVariable String latitude, @PathVariable String longitude, Model model){
//inject the data in the JSP
model.addAttribute("latitude", latitude);
model.addAttribute("longitude", longitude);
//return the html
return "private/private";
}
我想知道如何使用JavaScript代码中的参数访问此方法。
public String getCountry(@PathVariable String latitude, @PathVariable String longitude, Model model);
最佳答案
如果要以JSON格式获取结果,则可以按以下方式更改控制器,@Controller
@RequestMapping("/test")
public class TestServlet {
@ResponseBody
@RequestMapping("/country", method = RequestMethod.GET, produces = "application/json")
public Map getCountry(@PathVariable String latitude, @PathVariable
String longitude){
final Map messageObject = new HashMap<>();
messageObject.put("latitude", latitude);
messageObject.put("longitude", longitude);
//return the html
return messageObject;
}
然后在客户端,
$.getJSON("/country", {latitude: , longitude: }, function(data) {
if (data != null) {
for(key in data){
var lat = data[latitude];
var long = data[longitude];
}
}
});