本文介绍了Ajax每次点击都会增加响应数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的ajax请求(它只是发送表单),当我单击按钮时会调用它.问题是当我单击登录并失败时,php确实回显失败",当我再次单击它时,php两次回声"它,然后重复三次,等等.直到刷新页面然后重置计数器" .它位于$(document).ready()内部,并使用POST. 我的代码:
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代码编辑"
$('#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;
});
}
编辑#2(代码说明)
我希望它如何工作.
- 用户填写表格(有效)
- 用户单击注册"按钮,php将执行数据库代码(如果所有内容均已创建,则创建用户)
- 如果出现类似用户名的错误,php会回显用户名已被使用"
- 现在是问题所在.如果用户要使用其他用户名,然后单击注册",并且用户填写的数据正常,则php会回显用户创建",然后回显用户名已被使用".这是因为ajax发送了两次表单.如果用户再次填写错了,然后正确,他将获得"User Created"(用户创建)和2x"Username hastake"(用户名已被使用)的信息,然后反复进行直到刷新页面.
- User fills the form (this works)
- User clicks "Register" button, php does the database code (if everything is filled right the user is created)
- If there is an error like username taken php does echo "Username already taken"
- 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.
推荐答案
您多次绑定到Submit事件.之前
You're binding to the Submit event multiple times.Before
frm.submit()
使用:
frm.unbind("submit");
这篇关于Ajax每次点击都会增加响应数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!