【发布时间】:2017-06-04 14:48:35
【问题描述】:
这个问题是Returning ModelAndView in ajax spring mvc的后续问题
正如唯一的答案所说,我们需要从 Controller 而不是 ModelAndView 返回 json。所以问题是
- 如何返回 ModelAndView ?
- 页面将如何呈现:-
- 是否必须在ajax调用的成功部分进行处理
- 或者 Spring Controller 会像在 Spring MVC 中一样返回页面
- 如何在 Controller 中读取来自 ajax 的发布数据。
更新 1: 如前所述,我尝试了示例。这是我的代码。
@Controller
public class AppController
{
@RequestMapping(value="/greeting",method=RequestMethod.POST)
@ResponseBody
public ModelAndView getGreeting(@RequestBody String json) throws IOException
{
JSONObject inputjsonObject = new JSONObject(json);
String name = inputjsonObject.getString("name");
ModelAndView modelAndView = new ModelAndView();
String result = "Hi "+name;
modelAndView.addObject("testdata", result);
modelAndView.addObject("user", getPrincipal());
modelAndView.setViewName("greetingHtmlPage");
return modelAndView;
}
// other stuff
}
在上述控制器方法中,我可以成功获取数据。此方法是从 home.html 上的 javascript 调用的。下面是javascript函数
function callGreeting(){
var nameData={
name : document.getElementById("name").value
}
var dataInJson = JSON.stringify(nameData);
var csrf_token = document.getElementById("token").value;
$.ajax({
type: 'POST',
url: "greeting",
data: dataInJson,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function (response) {
document.open();
document.write(response);
document.close();
},
error: function (data) {
alert("failed response");
}
}); }
我已经成功渲染了页面。但是即使在加载新页面后,应用程序的 url 也不会从 AjaxSpringMVC:8080/home 更改为 AjaxSpringMVC:8080/greeting。如果在没有 Ajax 的情况下使用,这在 Spring MVC 中会自行发生。
【问题讨论】:
标签: ajax spring spring-mvc