jQuery的$就帖子多次(一个额外的后以后每次提交) [英] jquery $.ajax posts multiple times (one extra after each subsequent submit)

查看:111
本文介绍了jQuery的$就帖子多次(一个额外的后以后每次提交)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我忘记密码的形式,jQuery的阿贾克斯后触发多次(多了一个后,每提交)。因此,如果用户输入一个无效的电子邮件3次,然后一个有效的电子邮件,用户获得4密码更改电子邮件。好像事件被每个引发错误的时间堆积,和他们都得到下一个发射提交。这里是我的所有相关code。我在做什么错了?

JS

  RetrievePassword =功能(){
        变量$ =弹出$(#的fancybox-外);
        变种形式= $ popup.find(形式);
        form.submit(函数(五){
            VAR数据= form.serialize();
            VAR URL = form.attr('行动');
            $阿贾克斯({
                键入:POST,
                网址:网址,
                数据:数据,
                数据类型:JSON
                成功:函数(响应){
                    ShowMessageBar(response.Message);
                    $ .fancybox.close()
                },
                错误:功能(XHR,状态,错误){
                    ShowMessageBar(xhr.statusText);
                }
            });
            返回false;
        });
    };

MVC控制器/ ACTION

  [HandlerErrorWithAjaxFilter,HttpPost]
        公众的ActionResult RetrievePassword(字符串email)
        {
            用户的用户= _userRepository.GetByEmail(电子邮件);            如果(用户== NULL)
                抛出新ClientException(您输入在我们的系统中不存在的电子邮件请输入您用于注册的电子邮件地址。);            字符串randomString = SecurityHelper.GenerateRandomString();
            user.password的= SecurityHelper.GetMD5Bytes(randomString);
            _userRepository.Save();            EmailHelper.SendPasswordByEmail(randomString);            如果(Request.IsAjaxRequest())
                返回JSON(新JsonAuth {成功= TRUE,消息=您的密码已成功重置我们已经通过电子邮件发送您的新密码。RETURNURL =/首页/});
            其他
                返回查看();
        }

HandlerErrorWithAjaxFilter

 公共类HandleErrorWithAjaxFilter:HandleErrorAttribute
    {
        公共BOOL ShowStackTraceIfNotDebug {搞定;组; }
        公共字符串的ErrorMessage {搞定;组; }        公共覆盖无效onException的(ExceptionContext filterContext)
        {
            如果(filterContext.HttpContext.Request.IsAjaxRequest())
            {
                VAR内容= ShowStackTraceIfNotDebug || filterContext.HttpContext.IsDebuggingEnabled? filterContext.Exception.StackTrace:的String.Empty;
                filterContext.Result =新ContentResult类型
                {
                    的ContentType =text / plain的,
                    内容=内容
                };                字符串消息=的String.Empty;
                如果(!filterContext.Controller.ViewData.ModelState.IsValid)
                    消息= GetModeStateErrorMessage(filterContext);
                否则,如果(filterContext.Exception是ClientException)
                    消息= filterContext.Exception.Message.Replace(\\ r,即).Replace(\\ n,);
                否则,如果(!string.IsNullOrEmpty(的ErrorMessage))
                    消息=的ErrorMessage;
                其他
                    消息=错误而attemting执行的最后一个动作发生对不起给您带来不便。                filterContext.HttpContext.Response.Status =500+消息;
                filterContext.ExceptionHandled = TRUE;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = TRUE;
            }
            其他
            {
                base.OnException(filterContext);
            }
        }        私人字符串GetModeStateErrorMessage(ExceptionContext filterContext)
        {
            字符串的errorMessage =的String.Empty;
            的foreach(在filterContext.Controller.ViewData.ModelState.Keys VAR键)
            {
                VAR误差= filterContext.Controller.ViewData.ModelState [关键] .Errors.FirstOrDefault();
                如果(错误!= NULL)
                {
                    如果(string.IsNullOrEmpty(的errorMessage))
                        的errorMessage = error.ErrorMessage;
                    其他
                        的errorMessage =的String.Format({0},{1}的errorMessage,error.ErrorMessage);
                }
            }            返回的errorMessage;
        }    }

下面是更多的JS。我使用插件的fancybox我的收藏夹。在找回密码链接上的登录收藏夹。

  $(文件)。就绪(函数(){    $(登录)。的fancybox({
        hideOnContentClick:假的,
        titleShow:假的,
        的onComplete':功能(){            $(#注册)。的fancybox({
                hideOnContentClick:假的,
                titleShow:假的,
                的onComplete':功能(){                }
            });            $(#retrievepassword)。的fancybox({
                hideOnContentClick:假的,
                titleShow:假的,
                的onComplete':功能(){                }
            });
        }
    });});


解决方案

我不是一个jQuery的专家,但看来对我来说,每一次的fancybox的onComplete火灾,需要添加(另一个)事件处理函数#retrievepassword和#注册...我缺少页面的HTML的休息,所以我不知道如果/加载登录对话框中的内容时,但下面可能会更好地工作:

  $(文件)。就绪(函数(){    $(登录)。的fancybox({
        hideOnContentClick:假的,
        titleShow:假的,
        的onComplete':功能(){        }
    });    $(#注册)。的fancybox({
        hideOnContentClick:假的,
        titleShow:假的,
        的onComplete':功能(){        }
    });    $(#retrievepassword)。的fancybox({
        hideOnContentClick:假的,
        titleShow:假的,
        的onComplete':功能(){         }
    });
});

On my forgot password form, the jquery ajax post is fired multiple times (one more after each submit). So if the user enters an invalid email 3 times, and then a valid email, the user gets 4 password-changed emails. Seems like the event gets stacked each time an error is thrown, and all of them get fired on the next submit. Here's all my relevant code. What am I doing wrong?

JS

 RetrievePassword = function () {
        var $popup = $("#fancybox-outer");
        var form = $popup.find("form");
        form.submit(function (e) {
            var data = form.serialize();
            var url = form.attr('action');
            $.ajax({
                type: "POST",
                url: url,
                data: data,
                dataType: "json",
                success: function (response) {
                    ShowMessageBar(response.Message);
                    $.fancybox.close()
                },
                error: function (xhr, status, error) {
                    ShowMessageBar(xhr.statusText);
                }
            });
            return false;
        });    
    };

MVC CONTROLLER/ACTION

[HandlerErrorWithAjaxFilter, HttpPost]
        public ActionResult RetrievePassword(string email)
        {
            User user = _userRepository.GetByEmail(email);

            if (user == null)
                throw new ClientException("The email you entered does not exist in our system.  Please enter the email address you used to sign up.");

            string randomString = SecurityHelper.GenerateRandomString();
            user.Password = SecurityHelper.GetMD5Bytes(randomString);
            _userRepository.Save();

            EmailHelper.SendPasswordByEmail(randomString);

            if (Request.IsAjaxRequest())
                return Json(new JsonAuth { Success = true, Message = "Your password was reset successfully. We've emailed you your new password.", ReturnUrl = "/Home/" });
            else
                return View();           
        }

HandlerErrorWithAjaxFilter

public class HandleErrorWithAjaxFilter : HandleErrorAttribute
    {
        public bool ShowStackTraceIfNotDebug { get; set; }
        public string ErrorMessage { get; set; }

        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var content = ShowStackTraceIfNotDebug || filterContext.HttpContext.IsDebuggingEnabled ? filterContext.Exception.StackTrace : string.Empty;
                filterContext.Result = new ContentResult
                {
                    ContentType = "text/plain",
                    Content = content
                };

                string message = string.Empty;
                if (!filterContext.Controller.ViewData.ModelState.IsValid)
                    message = GetModeStateErrorMessage(filterContext);
                else if (filterContext.Exception is ClientException)
                    message = filterContext.Exception.Message.Replace("\r", " ").Replace("\n", " ");
                else if (!string.IsNullOrEmpty(ErrorMessage))
                    message = ErrorMessage;
                else
                    message = "An error occured while attemting to perform the last action.  Sorry for the inconvenience.";

                filterContext.HttpContext.Response.Status = "500 " + message;
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            }
            else
            {
                base.OnException(filterContext);
            }
        }

        private string GetModeStateErrorMessage(ExceptionContext filterContext)
        {
            string errorMessage = string.Empty;
            foreach (var key in filterContext.Controller.ViewData.ModelState.Keys)
            {
                var error = filterContext.Controller.ViewData.ModelState[key].Errors.FirstOrDefault();
                if (error != null)
                {
                    if (string.IsNullOrEmpty(errorMessage))
                        errorMessage = error.ErrorMessage;
                    else
                        errorMessage = string.Format("{0}, {1}", errorMessage, error.ErrorMessage);
                }
            }

            return errorMessage;
        }

    }

Here's more JS. I'm using the fancybox plugin as my lightbox. The Retrieve Password link is on the login lightbox.

$(document).ready(function () {

    $(".login").fancybox({
        'hideOnContentClick': false,
        'titleShow': false,
        'onComplete': function () {       

            $("#signup").fancybox({
                'hideOnContentClick': false,
                'titleShow':false,
                'onComplete': function () {

                }
            });

            $("#retrievepassword").fancybox({
                'hideOnContentClick': false,
                'titleShow': false,
                'onComplete': function () {

                }
            });
        }
    });  

});

解决方案

I'm not a jQuery expert, but it would appear to me that every time fancybox onComplete fires , you add (another) event handler to #retrievepassword and #signup... I'm missing the rest of the html in the page, so i dont know if/when the login dialog content is loaded, but the following might work better:

$(document).ready(function () {

    $(".login").fancybox({
        'hideOnContentClick': false,
        'titleShow': false,
        'onComplete': function () {       

        }
    }); 

    $("#signup").fancybox({
        'hideOnContentClick': false,
        'titleShow':false,
        'onComplete': function () {

        }
    });

    $("#retrievepassword").fancybox({
        'hideOnContentClick': false,
        'titleShow': false,
        'onComplete': function () {

         }
    });
});

这篇关于jQuery的$就帖子多次(一个额外的后以后每次提交)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆