简体   繁体   中英

Passing PathVariable to AJAX controller

I want to be able to pass the value entered in the textbox, on a mouse click, to my AJAX controller.

Controller code:

@EnableWebMvc
@Controller
public class HelloWorldController {

    public static class User {

        private String name, surname;
        int age;

        public User(String name, String surname, int age) {
            this.name = name;
            this.surname = surname;
            this.age = age;
        }

        public int getAge() {
            return age;
        }

        public String getName() {
            return name;
        }

        public String getSurname() {
            return surname;
        }
    }

    @RequestMapping("/hello")
    public ModelAndView helloWorld() {
        return new ModelAndView("home/hello.jsp", "message", "Spring MVC Demo");
    }

    @RequestMapping(value = "/hello/{name}", produces = "application/json")
    public @ResponseBody User getUser(@PathVariable(value = "name") String name) {
        return new User(name, "Surname", 25);
    }
}

Relevant view code:

        $.getJSON("hello/", {name: $('#username').val()} , function(obj) {
                            $("ul").append("<li>"+obj.name+"</li>");
                        });

// ...

    <input type="text" name="username" id="username" >

So this doesn't work, when the button is clicked, nothing happens. However, when I change in my controller to @RequestParam it works, but I want it to work with @PathVariable so that the URL for the correct username gets displayed.

Where is the problem, how should I fix that?

It sounds like that because you're using GET method to pass your HTTP request the parameter (name) is passed via a query string.

That's why @RequestParam works and @PathVariable doesn't.

If you must do it with GET method then try to build your URL as follows:

/hello/" + $('#username').val() + "/"

and don't pass data with your ajax request .

Try to work with firebug or google developer tools in order to see what data is going to server and back to browser.

something like that:

$.getJSON(/hello/" + $('#username').val() + "/", 
    function(obj) {
         $("ul").append("<li>"+obj.name+"</li>");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM