jquery ajax经常发生重复提交表单的现象怎么办
$(".new").click(function(){ $("#EditForm").on('show', function(){ document.getElementById('id_date').value = ""; document.getElementById('id_content').value = ""; $(".save").click(function(){ var date_data = document.getElementById('id_date').value; var content_data = document.getElementById('id_content').value; var post_data = {'date':date_data, 'content':content_data, 'flag':'new'}; $.ajax({ type:'POST', url:'{% url diary_views_mydiary uid month %}', data:post_data, dataType:'json', async:false, success:function(ret){alert(ret);} }); }); $(".cancel").click(function(){ $("#EditForm").modal('hide'); }); }); });
def MyDiary(request, uid, month): if request.is_ajax(): flag = request.POST.get('flag') """New""" if flag == 'new': new_date = request.POST.get('date') new_content = request.POST.get('content') new_diary = Diary(user_id=uid, date=new_date, content=new_content) try: new_diary.save() ret = "1" return HttpResponse(ret) except: ret = "0" return HttpResponse(ret)
<div class="modal hide fade" id="EditForm"> <div class="modal-header"> <a class="close" data-dismiss="modal">×</a> <h3>新建</h3> </div> <div class="modal-body"> <form action="" method="POST"> <fieldset> {% csrf_token %} <div class="control-group"> <label class="control-label" for="id_date">日期</label> <div class="controls"> <input id="id_date" type="text" name="date" maxlength="50" class="required datepicker" /> </div> </div> <div class="control-group"> <label class="control-label" for="id_content">内容</label> <div class="controls"> <textarea id="id_content" rows="10" cols="40" name="content" class="span4 required"></textarea> </div> </div> </fieldset> </form> </div>
我使用的是django框架,经常发生提交一次就会保持好几条重复的条目……
我试过在回调函数里强制刷新页面,不过也没用,照样会有重复的。
请问需要怎么做?
你的事件绑定有问题吧,点击new多少次,就给 $(".save")绑定了多少次click事件,也就相当于执行了多少次click事件,导致发送了多少次ajax了。。
要取消原来绑定的click事件再绑定,要么就在$(function(){/*执行绑定*/});执行事件绑定只绑定一次
$(".new").click(function(){
$("#EditForm").on('show', function(){
document.getElementById('id_date').value = "";
document.getElementById('id_content').value = "";
$(".save").unbind('click').click(function(){
var date_data = document.getElementById('id_date').value;
var content_data = document.getElementById('id_content').value;
var post_data = {'date':date_data, 'content':content_data, 'flag':'new'};
$.ajax({
type:'POST',
url:'{% url diary_views_mydiary uid month %}',
data:post_data,
dataType:'json',
async:false,
success:function(ret){alert(ret);}
});
});
$(".cancel").unbind('click').click(function(){
$("#EditForm").modal('hide');
});
});
});