我有这样的登录表单:
<form:form modelAttribute="user" method="post" enctype="application/x-www-form-urlencoded">
<form:input path="userEmailId" />
<form:password path="userPassword />
<input type="submit" value="sign up" />
</form:form>
这是我的user.java
的setter和getters
public String getUserEmailId() {
return userEmailId;
}
public void setUserEmailId(String userEmailId) {
this.userEmailId = userEmailId;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
点击注册后,我希望首先将此值转换为json,然后通过post方法将此值发送到服务器。我想使用RESTful WEB
服务来实现这一目标。有什么想法吗?
答案 0 :(得分:2)
您可以使用JSON
将表单序列化为json object
,然后使用AJAX
向您的网络服务发送帖子请求:
$(function() {
$('#formId').submit(function(event) {
event.preventDefault(); // prevent this form from being submited
var userJson = JSON.stringify(jQuery('#formId').serializeArray());
$.ajax({
type: "POST",
url: "/Path/To/Your/Web/Service",
data: userJson,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);//handle it in a proper way
},
failure: function(errMsg) {
alert(errMsg);//handle it in a proper way
}
});
return false;
});
});
然后在你的WebService上,你应该有一个方法来处理这个帖子请求:
@Controller
@RequestMapping("/path/to/your/web/service")
public class WebServiceController{
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<String> handleLogin(@RequestBody User user){
//user contains data passed from UI form. Check it against your repository(database ? )
}
}
请注意,此示例只是一个足够简单的示例,并未考虑与安全性相关的任何方面。
答案 1 :(得分:0)
function getFormData($form){
// Make sure the checked checkboxes value is true
$.each($form.find("input[type='checkbox']:checked"), function(i, c){
$(c).val(true);
});
// Serialize
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
if(indexed_array[n['name']]){
// concat
var valueArray = [indexed_array[n['name']]];
indexed_array[n['name']] = valueArray.concat(n['value']);
} else {
indexed_array[n['name']] = n['value'];
}
});
// Add the unchecked checkboxes
$.each($form.find("input[type='checkbox']:not(:checked)"), function(i, c){
indexed_array[$(c).attr('name')] = "false";
});
return indexed_array;
}
//...
$.ajax({
url: entityUrl,
method: "POST",
contentType: "application/json",
data: JSON.stringify(getFormData($(form))),
dataType: "json",
success: success,
error: error
});