我使用jQuery将数据发送到Spring MVC后端。我的Spring控制器方法看起来像这样:
@RequestMapping(value = "/add",method=RequestMethod.POST)
public @ResponseBody Response addAnsw(HttpServletRequest request, HttpServletResponse response) {
Response answer = new Response();
String name = request.getParameter("answer");
System.out.println(name);
return answer;
}我的ajax方法如下:
function doAjaxPost() {
var search = {
answer : $("#currentanswer1").val()
}
alert(search.answer);
$.ajax({
type: 'POST',
url: 'add',
contentType : 'application/json; charset=utf-8',
data: JSON.stringify(search),
dataType : 'json',
success: function(data){
var json = "<h4>Ajax Response</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#info').html(json);
console.log("SUCCESS : ", data);
},
error: function(e){
$('#info').html("Sorry, there is something wrong with the data provided.");
alert('Error: ' + e);
}
});
}问题是,答案是返回值,函数以成功告终,但json中的字符串" answer“为空。
例如answer = abc (带警报的打印"abc“)和JSON看起来像这样:
{
"answer": null
}我没有在我的jsp中使用表单属性(由于另一个jQuery逻辑,它似乎不适用于表单属性)。我遗漏了什么?提前感谢!
发布于 2018-01-09 09:01:11
由于Response是一个自定义类,我猜测你的问题是你没有赋值,你只是创建了对象实例。直到你在这里的默认构造函数上赋值。你只是用它做了一个实例
Response answer = new Response();您没有设置任何值。出于测试目的,请尝试如下所示的内容
public @ResponseBody Map<String,String> addAnsw(HttpServletRequest request, HttpServletResponse response) {然后赋值
Map<String,String> test = new HashMap<String,String>();
test.put("answer","hi");
return test;如果你想让你的响应起作用,你可以在默认构造函数的answer中设置一个值。或者创建自定义构造函数。或者提供一个setter,以便能够在
public Response() {
this.answer= "My Cool answer"; // Asuming answer is a String
}要在json中接收来自客户端的数据,您可以执行以下操作
@RequestMapping(value = "/add",method=RequestMethod.POST)
public Response addAnsw(@RequestBody YourCustomClass yourRequest) {请注意,YourCustomClass必须具有所有的getter和setter,或者应该进行相应的注释,以便Jackson可以反序列化您发送到服务器的内容。
希望能有所帮助
https://stackoverflow.com/questions/48159644
复制相似问题