我有一个按钮如何防止重复发送ajax jQuery?
<span class="btn btn-primary" id="open-label"><i class="icon-plus icon-white"></i> Add label</span>
其打开模态窗口(http://twitter.github.com/bootstrap/javascript.html#modals)
<div id="ajax-labels"></div>
<div id="labels-modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="header">Add label</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" id="name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="color">Color</label>
<div class="controls">
<input type="text" id="color" name="color" value="#a5f3d4" size="6" class="iColorPicker" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="submit-label"><i class="icon-ok icon-white"></i> Add label</button>
</div>
</div>
<script>
function append_labels() {
$("#ajax-labels").empty();
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "get_labels"
},
success: function (html) {
labels = $.parseJSON(html);
$.each(labels, function() {
$("#ajax-labels").append('<span class="label" id="' + this.id + '" style="background-color: ' + this.color + '">' + this.name + '<i id="edit-label" class="icon-pencil icon-white"></i></span> ');
});
}
});
}
$('span#open-label').click(function() {
$('#labels-modal').modal('show');
$('#labels-modal #submit-label').click(function() {
$('#labels-modal #submit-label').prop('disabled', true);
var name = $('#labels-modal #name').val().trim();
var color = $('#labels-modal #color').val().trim();
if (name != '' || color != '') {
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "add_label",
name: name,
color: color
},
success: function() {
$('#labels-modal').modal('hide');
append_labels();
}
});
} else {
return false;
}
});
});
</script>
“添加标签”和jQuery发送请求填写标签,用户点击后,发送后,脚本关闭模态刷新(在ajax)标签列表。问题 - 如果用户快速点击“添加标签”,脚本将重复发送表单,并在数据库中响应双打。我如何防止这种情况?
我做这一行'$(“#标签,模态#提交标签” ).prop('disabled',true); ' – Nolik 2013-02-18 20:15:10
并且该按钮被禁用?另一方面,在一个中有多个ID选择器是多余的。 $(“#id1#id2”)将与$(“#id2”)相同,因为ID被认为始终是唯一的。最快的jQuery选择器是简单地提供一个ID。通常,添加附加信息会减慢选择器的速度。 – 2013-02-18 20:18:04
我知道我只能在选择器上使用一个val,但对我来说,理解起来更容易;)是的,点击后的按钮变为禁用状态,但是我转向按几次:) – Nolik 2013-02-18 20:24:50