我有一個按鈕如何防止重複發送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