调用AJAX方法时获得400(错误请求)

时间:2018-12-21 07:37:36

标签: java jquery json ajax spring

我正在借助按钮的onClick()事件来调用AJAX方法。

 function submitDateFunction()
 {
   var previousExceptions=new Object();
  previousExceptions.batchId=batchId;
  previousExceptions.dateFrom=dateFrom;
  previousExceptions.dateTo=dateTo;
 $.ajax({
        type:"POST",
        url : 'getPreviousExceptions/',
        dataType:'json',
        data: JSON.stringify(previousExceptions),
        contentType : 'application/json',
        success : function(data) {
        alert("success");

        },
         error: function(jqXHR, exception) { 
                alert(jqXHR.status); 
            } 
    });

我的Spring控制器方法

@RequestMapping(value={"batchdetails/previousExceptions/getPreviousExceptions"},method=RequestMethod.POST)
@ResponseBody
    public List<BatchExceptionDetails> displayPreviousExceptions(@RequestBody PreviousException previousException)
{
    ...

    return batchExceptionDetails;

}

}

这是我的上一个例外课程

package com.bmdashboard.beans;

import java.util.Date;

public class PreviousException {

    private int batchId;
    private Date dateFrom;
    private Date dateTo;



    public PreviousException() {
        super();
    }
    public int getBatchId() {
        return batchId;
    }
    public void setBatchId(int batchId) {
        this.batchId = batchId;
    }
    public Date getDateFrom() {
        return dateFrom;
    }
    public void setDateFrom(Date dateFrom) {
        this.dateFrom = dateFrom;
    }
    public Date getDateTo() {
        return dateTo;
    }
    public void setDateTo(Date dateTo) {
        this.dateTo = dateTo;
    }
    @Override
    public String toString() {
        return "PreviousException [batchId=" + batchId + ", dateFrom="
                + dateFrom + ", dateTo=" + dateTo + "]";
    }



}

调用JavaScript函数的按钮

<input type="submit" value="Submit" onclick="submitDateFunction()" >

我通过以下方式获得价值

 var batchId=document.getElementById('batchIdForAjax').innerHTML;
 var dateFrom;
 var dateTo;

  $(function() {
    $( "#datepickerFrom" ).datepicker({ dateFormat: "yy-mm-dd" });
    $("#datepickerFrom").on("change",function(){
       dateFrom = $(this).val();

    });
});

$(function() {
    $( "#datepickerTo" ).datepicker({ dateFormat: "yy-mm-dd" });
    $("#datepickerTo").on("change",function(){
        dateTo = $(this).val();

    });
});

通过Google Chrome开发者工具控制台进行调试时,出现错误POST http://.../getPreviousExceptions/ 400(错误请求)。

1 个答案:

答案 0 :(得分:0)

我从java.util.date将dateFrom和dateTo的数据类型更改为String,并如下修改了我的AJAX

var previousExceptions = {
      "batchId" : batchId,
      "dateFrom":dateFrom,
      "dateTo":dateTo     
   };


$.ajax({
            type:"POST",
            url : 'getPreviousExceptions/',
            dataType: 'json',
            data: JSON.stringify(previousExceptions),
            contentType : 'application/json; charset=utf-8',
            success : function(data) {
...