【发布时间】:2014-04-14 17:45:25
【问题描述】:
我使用 XmlHttpRequest 向服务器发送请求。请求在服务器上处理,服务器希望发送错误 带有解释性文本的响应(在正文中)。我尝试了许多不同的响应代码,但在客户端(Chrome v33 左右)上,XHR 对象的响应始终为空。
客户:
var formItem = document.forms.namedItem("regform"),
formData = null;
/* -----------------------------------------------------------------
* General validation - after all the above
* ----------------------------------------------------------------- */
if (! formItem.checkValidity())
{
setup_register();
return;
}
formData = new FormData(formItem);
var req = new XMLHttpRequest(),
url = "http://" + host + "...whatever.../registration";
console.log("Start Registration " + formData);
req.open("POST", url, true);
req.onreadystatechange = function () {
if (this.readyState == 4)
{
if (this.status == 200)
{
console.log("Registration finished OK");
window.return_window.postMessage("Done", '*');
window.close();
}
else
{
console.error("Registration failed" + req.status + " Text:" + req.responseText);
return;
}
}
};
req.send(formData);
服务器:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/registration")
public ClientIdentification registration(
@FormDataParam("username") String username,
@FormDataParam("firstname") String firstname,
@FormDataParam("password") String password,
@FormDataParam("lastname") String lastname,
@FormDataParam("verifypassword") String verifypassword,
@FormDataParam("businessname") String businessname,
...
...
throw new PisRsMessageException(e.getMessage(), HttpServletResponse.SC_FORBIDDEN);
其中 PisRsMessageException 是 Jersy 的 WebApplicationException 的简单包装器
我已对此进行了嗅探,以确保正确发送响应。但是 req.responseText 始终为空。
我看到这或多或少是对 W3C 标准的简单解释——如果服务器返回错误,responseText 应该为空。那没有帮助。我需要有一种返回错误的方法,但仍然有解释性文字。
见:http://www.w3.org/TR/2014/WD-XMLHttpRequest-20140130/#the-responsetext-attribute
回退是总是返回 200,但如果没有必要,我不想这样做。
【问题讨论】:
标签: javascript ajax xmlhttprequest