[英]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.