我正在使用 backbone 开发一个网络应用程序。在我的主干 View 中,我正在使用事件表单提交。第一次加载 View 时,表单提交就可以了。但是当我在路由器之间切换然后提交我的表单时,它会发送多个相同的 ajax 请求。
我的观点如下..
var View_AdvanceSearchArea = Backbone.View.extend({
el: '.page',
events: {
'change #genderID': 'genderChange',
'change #areaID': 'areaChage',
'submit #advanceSearchForm': 'formSubmit'
},
genderChange: function() {
$.ajax({
url: 'getBodyHeightByGender',
type: 'POST',
data: '&genderID=' + $('#genderID').val(),
success: function(res) {
$('#bodyHeightID').html(res);
}
});
$.ajax({
url: 'getAgeByGender',
type: 'POST',
data: '&genderID=' + $('#genderID').val(),
success: function(res) {
$('#seventhDigitID').html(res);
}
});
},
areaChage: function() {
$.ajax({
url: 'getSubAreaByArea',
type: 'POST',
data: '&areaID=' + $('#areaID').val(),
success: function(res) {
$('#subAreaID').html(res);
}
});
},
formSubmit: function(e) {
e.preventDefault();
var formData = $('#advanceSearchForm').serializeArray();
var vAdvanceSearchResult = new View_AdvanceSearchResult();
vAdvanceSearchResult.render(formData);
},
render: function() {
var $this = this;
var mAdvanceSearchForm = new Model_AdvanceSearchForm();
mAdvanceSearchForm.fetch({
success: function(res) {
var template = _.template($('#advance_search_area').html(), {res: res.attributes});
$this.$el.html(template);
}
});
}
});
问题是什么? 有什么帮助吗?
最佳答案
当您调用 View 时,它的事件每次都会绑定(bind)到 DOM 元素。 初始化 View 时,您必须从 DOM 元素取消委托(delegate)事件。
在您的 View 中尝试以下代码..
var View_AdvanceSearchArea = Backbone.View.extend({
el: '.page',
initialize: function() {
$(this.el).undelegate('#advanceSearchForm', 'submit');
$(this.el).undelegate('#genderID', 'change');
$(this.el).undelegate('#areaID', 'change');
},
//here is your rest of code
希望它对你有用..
关于javascript - 在主干中提交表单时触发了多个相同的 ajax 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18534546/