我正在尝试使用model.addAttribute("myModel",mymodelvariable);
将我用spring加载的模型解析为ajax调用(该模型在表单中使用)。
是否可以调用Spring控制器并发送该模型现在将数据发送回我的控制器?否则,如何使用ajax将表单数据作为对象解析为我的控制器?
这是我使用@Html尝试的内容:
$('#sampleForm').submit(
function(event) {
var data = @Html.Raw(Json.Encode(Model));
$.ajax({
url: 'http://localhost:8080/hellohello',
type : "POST",
data : data,
beforeSend: function (xhr) {
xhr.setRequestHeader(header, token);
},
success : function(response) {
$('#reloading').html(response);
},
error : function(err) {
alert("not working")
console.log("not working. ERROR: "+JSON.stringify(err));
}
});
return false;
});
控制器:
@CrossOrigin(origins = "http://localhost:8080")
@ResponseBody
@RequestMapping(value = "/hellohello",method = RequestMethod.POST)
public ModelAndView step1(@ModelAttribute Mymodelvariable mymodelvariable){
//do stuff and return model
}
答案 0 :(得分:1)
尝试一下可能会帮助您
$('#sampleForm').submit(
function(event) {
var data={
"name":$('#name').val(),
"age":$('#age').val(),
"xyz":$('#xyz'+str).val(),
"xyz":$('#xyz'+str).val(),
"xyz":$('#xyz'+str).val(),
"xyz":$('#xyz'+str).val(),
"xyz":$('#xyz'+str).val(),
}
$.ajax({
url : "././hellohello",
type : "POST",
contentType : 'application/json; charset=utf-8',
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader(header, token);
},
success : function(response) {
$('#reloading').html(response);
},
error : function(err) {
alert("not working")
console.log("not working. ERROR: "+JSON.stringify(err));
}
});
return false;
});
控制器类:
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/hellohello",method = RequestMethod.POST)
@ResponseBody
public ModelAndView step1(@RequestBody Modelclass mymodelvariable)throws
Exception{
//do stuff and return model
}