0

This is my controller:

@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";
}

I want to know how to access this method with parameter from javascript code.

 public String getCountry(@PathVariable String latitude, @PathVariable String longitude, Model  model);

3 Answers 3

1

Something like this would do

 $.ajax({
     type : "GET",
     url : "http://<server>:<port>/test/country/<latitudevalue>-<longitudevalue>",
     contentType: "application/json",
     dataType: "json",
     success : function (data, status) {
        ......
     },
     error : function (status) {
        ....
     }
 });
Sign up to request clarification or add additional context in comments.

Comments

1

I fear that @PathVariable has some problems to correctly recognise variables split by '-'. I'd use other standard characters for this task like '/' or '&'.

Also I'd specify the HTTP method in the @RequestMapping annotation like:

 @RequestMapping(value = "/country/{latitude}-{longitude}", method = RequestMethod.GET)

The js ajax call would be something like:

$.ajax({
 type : "GET",
 contentType: "application/json",
 dataType: "json",
 url : "/test/country/" + lat + "-" + lon,
 success : function (data, status) {
    /*CODE*/
 },
});

Comments

0

If you want to get the result in JSON then you could change the controller as follows,

@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;
}

Then on the client side,

$.getJSON("/country", {latitude: <latitude>, longitude: <longitude>}, function(data) { 

        if (data != null) {
          for(key in data){
           var lat = data[latitude];
           var long = data[longitude];
          }
        }
     });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.