dongyuan1983 2014-07-13 16:37
浏览 104
已采纳

ajax会增加每次点击的响应次数

I've got simple ajax request (it just sends form) and it is called when I click the button. The problem is when I click login and it's failed, php does echo "FAIL" and when I click it again then php "echoes" it two times, then three times etc. It happens until I refresh the pages then "the counter" resets. It is inside $(document).ready() and it uses POST. My code:

EDIT#1 "CODE EDIT"

$('#register').click(function (event)
{
    if (true)
    {
        var frm = $('#registerForm');
        alert('debug1'); //DOESN'T REPEAT
        frm.submit(function (ev) // THIS FUNCTION REPEATS, DONT KNOW WHY.
        {
        alert('debug2'); //DOES REPEAT
            $.ajax(
            {
                type: frm.attr('method'),
                url: frm.attr('action'),
                data: frm.serialize(),
                success: function (text)
                {
                    $("#reg_dialog").dialog({
                    hide:{effect:"drop",duration: 1000}}).dialog('close');
                    $("#info").html(text).fadeIn(400).delay(2500).fadeOut(500,function(){
                        if(text!=="User Created"){
                        location.reload(); // THIS ONE RESETS "THE COUNTER" AS I SAID BEFORE, BUT I DONT WANT TO RELOAD WHOLE PAGE
                        }})
                }
            });
            ev.preventDefault();
            return false;
        });
    }

EDIT #2 (code explanation)

How I want this to work.

  1. User fills the form (this works)
  2. User clicks "Register" button, php does the database code (if everything is filled right the user is created)
  3. If there is an error like username taken php does echo "Username already taken"
  4. Now here is the problem. If user wants to use other username and he clicks "Register" and user-filled data is ok, the php does echo "User Created" and then "Username already taken". This is because ajax sends the form two times. If user have filled it wrong again and then right he gets "User Created" and 2x "Username already taken" and it goes like that over and over again until he refreshes the page.
  • 写回答

2条回答 默认 最新

  • doudang4857 2014-07-13 17:22
    关注

    You're binding to the Submit event multiple times. Before

    frm.submit() 
    

    use:

    frm.unbind("submit");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP