Sha*_*aoz 17 jquery file-upload jquery-plugins jquery-forms-plugin ajax-upload
似乎Jquery.Form插件中没有错误处理工具,这非常令人沮丧.即使文档说我们可以使用$ .ajax选项,但当服务器返回错误时,我仍然无法使用'error'选项,尤其是500和400系列.是不是这个插件无法处理来自服务器的任何错误,还是一个bug等等?有人可以告诉我如何处理这个插件的错误(400,500等)?我需要你的帮助......我想要的只是一个简单的错误处理......谢谢.
$("#uploadingImg").hide();
var options = {//Define ajax options
type: "post",
target: "#responsePanel",
beforeSend: function(){
$("#uploadingImg").show();
},
complete: function(xhr, textStatus){
$("#uploadingImg").hide();
},
success: function(response, statusString, xhr, $form){
// I know what to do here since this option works fine
},
error: function(response, status, err){
// This option doesn't catch any of the error below,
// everything is always 'OK' a.k.a 200
if(response.status == 400){
console.log("Sorry, this is bad request!");
}
if(response.status == 601){
sessionTimedOut();
}
}
}
$("#polygonUploadForm").submit(function(){
$(this).ajaxSubmit(options); // Using the jquery.form plugin
return false;
});
Run Code Online (Sandbox Code Playgroud)
JCo*_*ton 49
jQuery Form Plugin 确实处理错误,文档说明它可以使用$ .ajax选项.但是插件将运行两种模式 - 普通和文件上传.您遇到的问题是因为您正在执行文件上传.(你没有说这个,但你有"#uploadingImg"和"#polygonUploadForm",并且,递归推理,你遇到了这个问题.)
这是常见的说法,但您无法使用AJAX上传文件.此解决方法是使用iframe.表单提交POST正常的HTTP请求并在iframe中加载服务器响应.该插件抓住了响应并瞧瞧.因为这是普通的HTTP请求,$ .ajax的规则和行为不适用(因为它没有被使用).Form插件唯一可以做的就是将它获得的成功视为成功.在代码术语中,文件上传永远不会触发分配给ajaxForm()或ajaxSubmit()的'error'属性.如果你真的想证明这不是一个AJAX请求,请在表单中附加一个ajaxComplete()处理程序(即完全独立于Form插件的方法).它也不会被触发.或者看看Firebug的Net-> XHR面板.
就是这样 - 上传不是AJAX请求.你能做的最好的事情就是在ajaxForm()/ ajaxSubmit()的'success'或'complete'回调中工作.您无法访问实际的HTTP响应代码,但您可以检查响应.如果响应为空或不符合您的预期,您实际上可以通过调用来触发"错误"回调xhr.abort().而不是做"if(良好的响应){yay!} else {oh no!}",调用abort()并触发'error'使得代码更清晰,更易理解恕我直言.这是一个代码示例:
$("#uploadForm").ajaxForm({
success: function(response, textStatus, xhr, form) {
console.log("in ajaxForm success");
if (!response.length || response != 'good') {
console.log("bad or empty response");
return xhr.abort();
}
console.log("All good. Do stuff");
},
error: function(xhr, textStatus, errorThrown) {
console.log("in ajaxForm error");
},
complete: function(xhr, textStatus) {
console.log("in ajaxForm complete");
}
});
Run Code Online (Sandbox Code Playgroud)
错误的响应将在控制台日志中打印出来:
[jquery.form] state = uninitialized
"NetworkError: 404 NOT FOUND - http://server/fileupload/"
[jquery.form] state = loading
[jquery.form] isXml=false
in ajaxForm success
bad or empty response
[jquery.form] aborting upload... aborted
in ajaxForm error
in ajaxForm complete
in ajaxForm complete
Run Code Online (Sandbox Code Playgroud)
我不知道为什么'完整'回调会运行两次 - 有人吗?最后一点,如果您问为什么jQuery或Form插件不能只读取iframe的HTTP头,请阅读此主题.
刚刚发现 jquery.form 插件本身不处理服务器错误,因为由于“文件输入”标记处理文件上传的方式,它无法访问响应标头。因此,我认为W3C需要审查这个麻烦的标签,它不仅不允许您使用 CSS 对其进行样式设置,而且也不会使服务器响应处理变得容易。
但一定有办法解决它......
如果我说错了,请告诉我,并让我知道您对这个“文件输入”标签的想法......