我正在使用标准表单/操作发布到一个安静的Web服务,我试图不使用ajax,因为表单的大小和构成。有没有办法将错误处理附加到表单提交?请参阅下面的当前代码。
<form id="theForm"
action="rest/url"
method="post"
enctype="multipart/form-data">
</form>
$("#theForm").submit(function(e){
// Can anything be done to handle 500s here?
});
这是休息服务。
@POST
@Path("/save")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void save(
@FormDataParam("iD") Integer iD,
....
@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail
{
// void to avoid redirect
// exceptions return 500
throw new ServerException(500);
}
答案 0 :(得分:2)
试试这个:
<form method="post" id="form>
</form>
Ajax代码:
$('#form').submit(function () {
$.ajax({
url: 'your_url.html',
data: 'some_data=somevalue',
success: function (response) {
// it was a success!
}
error: function () {
// it was an error!
}
});
});
请注意,您无法处理正常的提交过程! HTTP响应只能检查ajax请求。简单的表单提交无法处理!
您可以点击提交按钮执行上述代码!
如果您不想使用ajax,则需要使用服务器端代码。并从服务器检查HTTP Resonse!如果是500,则将用户重定向到另一个页面!但请记住,您无法使用jQuery检查HttpResponseCode的默认提交过程!
如果您开始了解web.config
,那就更好了。这是您管理错误的文件以及服务器如何响应错误和其他条件的其他自定义。
答案 1 :(得分:1)
您可以像这样处理每种类型的Ajax错误
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
答案 2 :(得分:0)
经过多次阅读后,我发现使用FormData对象是可行的。这甚至可以处理多重选择。这是代码:
<form id="theForm">
<input name="text" type="text">
<select name="fileType">
...
</select>
<input name="file" type="file">
</form>
jQuery
$("#theForm").submit(function(e){
e.preventDefault();
var theForm = new FormData($(this)[0]);
$.ajax({
url: '.../rest/save',
type: 'POST',
data: theForm,
cache, false,
contentType: false,
processData: false
});
return false;
});
泽西岛资源
@POST
@Path("/save")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void save(
@FormDataParam("text") String text,
....
@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail){
log.info(fileDetail.getFileName());
// exceptions return 500
throw new ServerException(500);
}