简体   繁体   English

将PathVariable传递给AJAX控制器

[英]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. 我希望能够通过单击鼠标将在文本框中输入的值传递给我的AJAX控制器。

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. 但是,当我将控制器更改为@RequestParam它可以工作,但是我希望它与@PathVariable一起工作,以便显示正确username的URL。

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. 这听起来像是因为您正在使用GET方法传递HTTP请求,而参数(名称)是通过查询字符串传递的。

That's why @RequestParam works and @PathVariable doesn't. 这就是@RequestParam起作用而@PathVariable不能起作用的原因。

If you must do it with GET method then try to build your URL as follows: 如果必须使用GET方法执行此操作,请尝试按以下方式构建URL:

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

and don't pass data with your ajax request . 并且不要用你的ajax请求传递数据

Try to work with firebug or google developer tools in order to see what data is going to server and back to browser. 尝试使用Firebug或Google开发人员工具,以查看将要发送到服务器并返回到浏览器的数据。

something like that: 像这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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