AJAX回调中的alert()显示[Object object]

时间:2017-11-08 14:18:37

标签: jquery ajax spring-mvc

我正在调用以下函数来在Spring Controller中执行操作。问题是alert消息不包含我发送的消息,但打印[Object object]。有没有办法发送特定的消息,根据结果,打印它还发送状态代码?

function saveButton(button) {
  var data = gatherData(button);
  $.ajax({
    type: "POST",
    url: '/editRecord',
    data: data,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function(response) {
      alert(response);
    },
    error: function(error) {
      alert(getData().done(error));
    }
  });
}
@RequestMapping(value = "/editRecord", method = RequestMethod.POST)
public @ResponseBody
String editRecord(HttpServletRequest httpRequest) 
{
  Map<String, String[]> map = httpRequest.getParameterMap();

  // do stuff

  String messageToReturn = "";
  if (userService.updateTable(pr.getUpdateQuery(fileMap))) 
  {
    messageToReturn = "Operation was successful";
  } 
  else
    messageToReturn = "Operation failed";

  return messageToReturn;
}

4 个答案:

答案 0 :(得分:0)

您的方法返回text(即messageToReturn)而不是JSON。您可以按如下方式生成text

@RequestMapping(value = "/editRecord", method = RequestMethod.POST, produces="text/plain")
public @ResponseBody String editRecord(HttpServletRequest httpRequest){}

在这种情况下,从AJAX方法中删除dataType: 'json'

但是如果你返回JSON,那么你可以用JSON格式输入它。

messageToReturn = "{\"check\":\"Operation was successful\"}"; //(without produces="text/plain")

然后像这样访问:

success: function(response) {
 console.log(response.check);
}

答案 1 :(得分:0)

我使用Jackson库的ObjectMapper(jackson-databind)完成了它。只需修改您的方法如下:

@RequestMapping(value = "/editRecord", method = RequestMethod.POST)
public @ResponseBody
String editRecord(HttpServletRequest httpRequest) 
{
  Map<String, String[]> map = httpRequest.getParameterMap();

  // do stuff

  String messageToReturn = "";
  if (userService.updateTable(pr.getUpdateQuery(fileMap))) 
  {
    messageToReturn = "Operation was successful";
  } 
  else
    messageToReturn = "Operation failed";

  ObjectMapper mapper = new ObjectMapper();
  String json = mapper.writeValueAsString(messageToReturn);
  return json;
}

答案 2 :(得分:0)

success: function(response) {
  alert(response.responseText);
},

答案 3 :(得分:-1)

您从弹簧控制器发送的数据可通过response.data获得。

success: function (response) {
  alert(response.data);
},
error: function (error) {
  alert(getData().done(error.data));
}