jQuery表单插件,无错误处理。

17
看起来Jquery.Form插件中没有错误处理功能,这非常令人沮丧。即使文档说我们可以使用$.ajax选项,但当服务器返回错误时,特别是500和400系列时,我仍然无法使用'error'选项。这个插件是否完全不能处理来自服务器的任何错误,还是一个错误等?请问有人能告诉我如何使用这个插件处理错误(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;
});
5个回答

49
jQuery表单插件确实可以处理错误,并且文档正确地声明它可以使用$.ajax选项。但是,插件将以两种模式运行——普通模式和文件上传模式。你遇到的问题是因为你正在进行文件上传。这是常见的陈述,但你不能通过AJAX上传文件。解决方法是使用iframe。表单提交POST一个正常的HTTP请求,并在iframe中加载服务器响应。插件获取响应并完成操作。由于这是正常的HTTP请求,所以$.ajax的规则和行为不适用(因为没有使用)。表单插件唯一能做的就是将其收到的任何内容视为成功。在代码方面,文件上传永远不会触发分配给ajaxForm()或ajaxSubmit()的'error'属性。如果你真的想证明这不是一个AJAX请求,请将ajaxComplete()处理程序附加到表单(即完全独立于表单插件的方法)。它也不会被触发。或者查看Firebug的Net->XHR面板。

那就这样 - 上传不是 AJAX 请求。最好的做法是在 ajaxForm()/ajaxSubmit() 的 'success' 或 'complete' 回调函数中工作。没有实际 HTTP 响应代码的访问权限,但您可以检查响应。如果响应为空或不符合预期,则可以通过调用 xhr.abort() 来触发 'error' 回调。与其执行 "if(good response) {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");
    }
});

一个错误的意愿响应将会在控制台日志中打印出这个内容:

[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

我不知道为什么“完成”回调会运行两次 - 有人知道吗? 最后一件事,如果你想知道为什么jQuery或表单插件不能读取iframe的HTTP头,请阅读这个线程


2
请注意,这只是在使用iFrame解决方法时出现的问题 - 也就是说,在不正确支持HTML5功能的浏览器中。(咳嗽ie咳嗽) - Robert Watkins
+1 我非常喜欢人们花时间分享他们的知识。非常感谢 @JCotton,我真的很感激你清晰而且信息量大的回答 :) - will824

1
Jquery表单插件处理服务器响应状态成功(代码200),我认为这些信息已经足够了。从那里,您可以在服务器端创建响应状态。
            return $this->returnJson(array(
                'response' => 'success',//error or whatever
                'data' => 'Succesfully saved in the database'
            ));

当然,returnJson是一个发送Json数据的函数(你可以构建一个或在方法内部执行)。
在前端成功处理时(响应为200时触发),你只需要检查你的状态字段(在这种情况下为'response'),以下是示例:
  var options = {
        dataType : 'json',
        success: handleResponse
    };


    function handleResponse (responseText, statusText, xhr, $form){

          if(responseText.response == 'success') {
                  //do something

                }else if(responseText.response == 'error'){
                    //do something

            }


    }

感谢您提供的好解决方案。 - Jude Niroshan

1

刚刚发现,jquery.form插件本身不处理服务器错误,因为它无法访问响应头,是由于'文件输入'标签处理文件上传的方式造成的。所以我认为W3C需要审查这个烦人的标签,它不仅让你无法使用CSS来设置样式,而且也不容易处理服务器响应。

但肯定有方法可以解决...

如果我说错了什么,请告诉我您对这个'文件输入'标签的想法...


0

在选项中

var options = { 
    target:        '#output2',    
    beforeSubmit:  showRequest,   
    success:       showResponse,  
timeout:    1000
}; 

在出现错误时,没有触发器调用。插件只会在出现500或404错误时挂起。 成功仅在“成功”上进行操作,因此目前我们只有这些。


0

对于仍然需要此功能的任何人,这是使其正常工作的方法

function submitForm()
{
    var isSuccess   = false,
        options = {
            url         : "posturl.php",
            type        : 'POST',
            dataType    : 'json',
            success:function(msg) {
                //set the variable to true
                isSuccess = true;

                //do whatever
            },
            complete: function () {
                if (isSuccess === false) {
                    //throw the error message
                }
            }
        };

    //Ajax submit the form
    $('#your_form').ajaxSubmit(options);

    // always return false to prevent standard browser submit and page navigation
    return false;
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接