验证表单中的所有输入后,我尝试将JSON发送到控制器(Spring-MVC Framework)。但是,我一直在获取空数据对象。
这是我的.js
文件
/**
*
*/
$(document).ready(function() {
alert('Running ... ');
});
function validateForm() {
var name = document.forms.myform.elements.name.value;
var email = document.forms.myform.elements.email.value;
var description = document.forms.myform.elements.description.value;
var error = 'has-error';
var ok = 'has-success';
if (!name || !email || !description) {
// alert(description);
if (!description) {
$('#description_form').addClass(error);
} else {
$('#description_form').removeClass(error).addClass(ok);
}
if (!name) {
$('#name_form').addClass(error);
} else {
$('#name_form').removeClass(error).addClass(ok);
}
if (!email) {
$('#email_form').addClass(error);
} else {
$('#email_form').removeClass(error).addClass(ok);
}
return false;
}
var frm = $(document.forms.myform);
$.ajax({
type: 'POST',
url: '/insert',
data: {
name: "Name",
email: "example@abc.com",
desc: "Not a real person"
},
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
beforeSend: function (data) {
console.log('Before sending data ... ');
console.log(data);
}
});
e.preventDefault();
return true;
}
对于控制器部分,使用org.json.JSONObject
库:
package gac.asr;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HomeController {
@RequestMapping(path = "/", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/insert", method = RequestMethod.POST)
public @ResponseBody void getData(JSONObject json) {
System.out.println(json.toString());
}
}
运行应用程序时,我从脚本中收到“正在运行...”消息。但是当我尝试打印来自脚本的数据时,我得到一个空的JSON对象“{}”。
编辑:
添加调用验证脚本的表单。
<form:form name="myform" class="form-horizontal" onsubmit="return validateForm();" method="POST" action="/insert">
<!--MORE CODE-->
</form:form>
答案 0 :(得分:2)
我会创建一个封装器来封装你的所有属性。我们称之为MyEntity
public class MyEntity implements Serializable{
private String name;
private String email;
private String desc;
//getters setters
}
在您的控制器中使用它
@RequestMapping(value = "/insert", method = RequestMethod.POST)
public void getData(MyEntity person) {
System.out.println(person.getName());
}
答案 1 :(得分:0)
在您的控制器中,您应该使用:
@RequestMapping(value = "/insert", method = RequestMethod.POST)
public String getData(
@RequestParam(value = "name", required = true,) String name,
@RequestParam(value = "email", required = true,) String email,
){
System.out.println(name);
...
}