将Json对象发送到Spring Controller

时间:2017-08-11 12:36:40

标签: json ajax spring spring-mvc

Hy guys。

我有这个js代码,我创建了一个通过Ajax函数发送到Spring控制器的对象:

$('#eventsdatageneral').on('click', '.btn.btn-info', function(event) 
            {
                var today_date = new Date().getTime(); 
                var dataToSend = new Object();
                dataToSend.dateToSend = today_date;
                dataToSend.nameToSend = host_name;
                dataToSend.typeToSend = type_name;
                console.log(dataToSend);
                event.preventDefault();

                //here starts the code to sending data to Spring controller
                $.ajax({
                        url: "../todaydatarecover.json",
                        type: "post",
                        data: dataToSend,
                        success : function() {

                            console.log("Invio riuscito.");
                            //console.log(moment(today_date).format('DD/MM/YYYY'));
                        }

                    });
            }); 

这是控制器:

@PostMapping(value="/todaydatarecover.json")
    @ResponseBody
    public ModelAndView todayInfoAndIdRecover(ModelAndView model, HttpServletRequest request,
            @RequestParam(name="dateToSend", required=false) long dateInBox,
            @RequestParam(name="nameToSend", required=false) String nameInBox,
            @RequestParam(name="typeToSend", required=false) String typeInBox) throws IOException
    {
        //First of all, we invoke getinfo methods to take info and id
        Timestamp date = new Timestamp(dateInBox); 
        Events event = networks.getInfoandId(nameInBox, typeInBox, date);

        //Second, we put this list in the model and set properties for jquery datatables
        model.addObject("data", event);

        //Verify id and info
        System.out.println("The info is: " + event.getInfo());
        System.out.println("The id is: " + event.getId());   

        //Finally, we return the model
        return model;
    }

当我尝试执行时,我得到了org.springframework.dao.EmptyResultDataAccessExceptionIncorrect result size: expected 1, actual 0;但是,如果我通过My​​SQL客户端查询数据库,我可以毫无问题地采取正确的结果。所以,有一行与我执行的查询匹配;这让我觉得问题是我如何创建Json对象和/或我将它发送给Controller。

我的错误是什么?

1 个答案:

答案 0 :(得分:1)

在发送包含数据信息的信息时,您无法使用vertical-align: top检索数据。您需要使用@RequestParam并使用三个变量创建和对象。

示例:

@RequestBody