[英]Calling Java code from JavaScript (Spring boot)
这是我的控制器:
@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);
这样的事情会做
$.ajax({
type : "GET",
url : "http://<server>:<port>/test/country/<latitudevalue>-<longitudevalue>",
contentType: "application/json",
dataType: "json",
success : function (data, status) {
......
},
error : function (status) {
....
}
});
我担心@PathVariable在正确识别由'-'分隔的变量时会遇到一些问题。 对于该任务,我会使用其他标准字符,例如'/'或'&' 。
我还要在@RequestMapping注释中指定HTTP方法,例如:
@RequestMapping(value = "/country/{latitude}-{longitude}", method = RequestMethod.GET)
js ajax调用类似于:
$.ajax({
type : "GET",
contentType: "application/json",
dataType: "json",
url : "/test/country/" + lat + "-" + lon,
success : function (data, status) {
/*CODE*/
},
});
如果您想以JSON格式获取结果,则可以按以下方式更改控制器,
@Controller
@RequestMapping("/test")
public class TestServlet {
@ResponseBody
@RequestMapping("/country", method = RequestMethod.GET, produces = "application/json")
public Map<String, String> getCountry(@PathVariable String latitude, @PathVariable
String longitude){
final Map<String, String> messageObject = new HashMap<>();
messageObject.put("latitude", latitude);
messageObject.put("longitude", longitude);
//return the html
return messageObject;
}
然后在客户端,
$.getJSON("/country", {latitude: <latitude>, longitude: <longitude>}, function(data) {
if (data != null) {
for(key in data){
var lat = data[latitude];
var long = data[longitude];
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.