jquery - 使用 jQuery 表单插件 (ajaxForm) 检测错误响应

标签 jquery asp.net-mvc error-handling httpresponse ajaxform

我正在使用 jQuery Form 插件来 ajaxify 文件上传控件。我正在返回要加载到 div 中的 html。

我无法检测到错误情况。

我有以下 ASP.NET MVC Controller 方法:

public ActionResult UploadDocument(int id)
{
    try
    {
        // ...blah
    }
    catch(Exception e)
    {
        // log e

        // these two lines are what I can't get working
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return null;
    }
    return PartialView("blah", model);
} 

在 jQuery 中

$documentForm.ajaxForm({
    beforeSubmit: function() { ... },
    success: function(response, status, xhr) {

        if (status == "error") {
            // this doesn't work, status is still "success"
        }

        if (!response || response == '') {
            // this doesn't work either, as the html response
            // seems to get wrapped in a <pre> tag
        }

        // this line is fine if the controller call was a success
        $container.find('.documentHistory').html(response);
    }   

如何向客户端发出服务器响应错误的警报?

最佳答案

恐惧,

这是我修改后的 jquery ajaxform 插件的实现:

(function($) {
    $.fn.ajaxify = function(options) {

        // Defaults and options
        var defaults = {
            method: '',
            action: '',
            dataType: null, // i.e. json, jsonp etc
            target: null, // target div for ajax return data
            errordiv: null,
            // callback functions
            onBeforeSend: function() { },
            onSubmit: function() { return true },
            onSuccess: function() { },
            onError: function() { }
        };
        var opts = $.extend({}, defaults, options);

        this.each(function() {
            $(this).bind('submit', function(event) {

                event.preventDefault();

                // Increase readability && scope
                FORM = $(this);

                // Mimic the normal onSubmit handler
                if (!opts.onSubmit.call(FORM[0])) { return; }

                // Determine the method && action
                var method = opts.method || FORM.attr('method') || 'GET';
                var action = opts.action || FORM.attr('action');
                var dataType = opts.dataType || "text";
                var target = opts.target || null;
                var errordiv = opts.errordiv || null;

                // Submit the form via ajax, with appropriate callback
                $.ajax({
                    type: method,
                    url: action,
                    data: FORM.serialize(),
                    dataType: dataType,
                    beforeSend: function() {
                        opts.onBeforeSend(FORM[0]);
                    },
                    success: function(data) {
                        if (target != null)
                            opts.onSuccess.call(FORM[0], data, target);
                        else
                            opts.onSuccess.call(FORM[0], data);
                    },
                    error: function(request, status, error) {
                        // Boil the ASP.NET AJAX error down to JSON.
                        //var err = eval("(" + request.responseText + ")");
                        // Display the specific error raised by the server
                        if (request.responseText == '') {
                            var loader = this;
                            setTimeout(function() { $.ajax(loader); }, 150);
                            //console.log(status + " : " + request.statusText + " : " + request.status);
                        }
                        else {
                            if (errordiv != null)
                                opts.onError.call(FORM[0], request.responseText, errordiv);
                            else
                                opts.onError.call(FORM[0], request.responseText);
                        }
                    }
                });
            });
        });

        // allow chaining
        return this;
    }
})(jQuery);

用法(其中<form id="ajaxify" method="post" action="<%=Url.Action("Test") %>">等..:

$(document).ready(function() {
    var options = {
        onSubmit: myOnSubmit,
        onBeforeSend: myBefore,
        onSuccess: myOnSuccess,
        onError: myOnError,
        target: "#myDiv",
        errordiv: "#errDiv"
    };
    $('#ajaxify').ajaxify(options);
});

function myOnSubmit() {
    var valid = true;
    var FORM = $(this);

    FORM.find('input').css('border-color', '#F0F0F0');
    // fake validation just to demonstrate
    FORM.find('input').each(function() {
        if ($(this).val() == '') {
            $(this).css('border-color', 'red');
            valid = false;
        }
    });
    return valid;
}

function myBefore() {
    alert("we");
}

function myOnSuccess(msg, target) {
    if (target == null) {
        // this could also be a manually entered target
        // i.e. $("#myTargetDiv").html(msg);
        alert("no target");
    }
    else
        //alert($(target).html());
        $(target).html(msg);
}

function myOnError(errorText, errorDiv) {
    $(errorDiv).html(errorText);
}

希望这应该引起思考......

关于jquery - 使用 jQuery 表单插件 (ajaxForm) 检测错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390319/

相关文章:

html - 使用 Bootstrap 将 CheckBox 右对齐

exception - PHPUnit 模拟异常

c - 我在使用 fopen 时遇到错误

javascript - 如何处理 knockout 订阅中的错误

jquery - 如何使用 JS-SDK 创建一个signed_request 通过 Ajax 传递给 PHP-SDK

javascript - 如何将 "attach"广告元素置于居中网站?

javascript - 使用 angularjs 将滚动事件绑定(bind)到选择元素

c# - 如何在 ASP MVC 中下载 NPOI 生成的 xls 文件

jquery - 使用 ASP.NET MVC 6 中的文件进行 Ajax 表单提交

javascript - 如何让 .remove() 与窗口对象一起使用