【发布时间】:2014-06-06 16:04:35
【问题描述】:
我想处理更新实体的 AJAX 请求。我真的不需要它来返回任何东西。问题是 Spring MVC 坚持发送重定向到同一个 URL(显然是在做它的 post-redirect-get 事情),浏览器尽职尽责地遵循。
我怎样才能让 Spring MVC 控制器方法完成并返回一些东西而不发送重定向?在网络上搜索只会引发无数关于如何进行重定向的讨论,而不是如何避免重定向。
这是对http://localhost:9090/pex/api/testrun/f0a80b46-84b1-462a-af47-d1eadd779f59e 的 PUT 请求,带有以下标头:
Host: localhost:9090
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: */*
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Length: 20
Content-Type: application/json
Referer: http://localhost:9090/pex/api/testrun/f0a80b46-84b1-462a-af47-d1eadd779f59e/visualizations/common-api?slas=lp,internal,external
X-Requested-With: XMLHttpRequest
Connection: keep-alive
Authorization: Basic xxxx
响应的状态码为“302 Found”,没有正文内容和这些标头:
Content-Language: "de"
Content-Length: "0"
Location: "http://localhost:9090/pex/api/testrun/f0a80b46-84b1-462a-af47-d1eadd779f59e"
Server: "Jetty(6.1.10)"
access-control-allow-origin: "*"
这是服务器端代码:
@RequestMapping(value = "/api/testrun/{testrunId}", method = RequestMethod.PUT, consumes = "application/json")
@ResponseBody
public Testrun updateOverview(@PathVariable("testrunId") final String testrunId, @RequestBody final String body) {
return testrunService.updateOverview(testrunId, body);
}
这是进行 AJAX 调用的 Javascript 代码:
$(document).ready(function() {
$("#update_name_form").submit(function (e) {
update_testrun($("#name"));
return false;
});
}
function update_testrun(element) {
var name = element.attr('name');
var new_value = element.val().trim();
var data = {};
data[name] = new_value;
$.ajax({url: config.urls.api.testrun + testrun.id,
type: "PUT",
contentType: "application/json",
data: JSON.stringify(data),
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
success: function (data, textStatus, jqXHR) {
testrun.overview[name] = new_value;
}
});
}
【问题讨论】:
-
@ResponseBody默认不发送重定向;这里可能正在发生其他事情。 -
使用
@ResponseBoby注解方法应该只返回一个序列化的Testrun对象而不重定向。您使用哪个代码进行 AJAX 调用? -
请添加更多详细信息,例如带有重定向响应的网络控制台信息。您发布的代码本身不会导致重定向。
-
@beerbajay:当然——但是这个“其他东西”会是什么?
-
一些配置会很好。
标签: java spring spring-mvc