如何将ajax传递给弹簧控制器

时间:2017-10-16 08:35:52

标签: javascript java jquery ajax spring-mvc

在Ajax页面中获取值

function GetInfoDivision()
{
     var data = $("#storeName").val();
    $.ajax({
        type : "POST",
        contentType : "application/json",   
        url : "hello",
        data : JSON.stringify(data),    
        dataType : 'json',              
        //timeout : 100000, 
        success : function(map) {
            console.log("SUCCESS: ", data);
            display(data);
        },
        error : function(e) {
            console.log("ERROR: ", e);
            display(e);
        },
        done : function(e) {
            console.log("DONE");
        }
    });

但Controller页面获取空值... Ajax数据值未传递给控制器​​

@RequestMapping(value="/hello", method = RequestMethod.POST)
        public String employeeLogin(ModelMap model, HttpServletRequest request) {
         String sname = request.getParameter("storeName");   
         System.out.println("s="+sname);    
            shopModel s = new shopModel();
              s.setStoreName(sname);

            //boolean result = employeeService.employeeLogin(employee);
              boolean result =false;
             if(result == true){

                    model.addAttribute("message", "Successfully logged in.");
             }
             else
             {
                model.addAttribute("message", "Username or password is wrong.");
            }
            return "redirect:index.jsp";
        }

see

3 个答案:

答案 0 :(得分:1)

您应该在控制器功能的参数中使用@RequestBody注释。

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html

@Autowired
private HttpServletRequest request;

@RequestMapping(value="/hello", method = RequestMethod.POST)
public String employeeLogin(@RequestBody ModelMap model) {      

答案 1 :(得分:1)

如果storeName只是一个字符串,那么您可以使用@RequestParam

@RequestMapping(value="/hello", method = RequestMethod.POST)
        public String employeeLogin(ModelMap model, HttpServletRequest request,
@RequestParam(value = "storeName", required = false) String storeName) {

String sname = storeName;
}

在Ajax通话中你可以像

一样打电话
url : "hello" + "?storeName=" + data

并删除Ajax调用中的以下属性

data : JSON.stringify(data), 

您的Ajax将如下所示:

function GetInfoDivision()
{
     var data = $("#storeName").val();
    $.ajax({
        type : "POST",
        contentType : "application/json",   
        url : "hello" + "?storeName=" + data,
        dataType : 'json',              
        //timeout : 100000, 
        success : function(map) {
            console.log("SUCCESS: ", data);
            display(data);
        },
        error : function(e) {
            console.log("ERROR: ", e);
            display(e);
        },
        done : function(e) {
            console.log("DONE");
        }
    });

答案 2 :(得分:0)

@RequestMapping(value = "hello", method = RequestMethod.POST)
@ResponseBody
public String methodname(@RequestParam("data") String data) {
    ...
    return "";
}