gpt4 book ai didi

javascript - 如何在 ajax 请求中保持代码干燥?

转载 作者:行者123 更新时间:2023-11-28 15:16:20 26 4
gpt4 key购买 nike

如以下代码所示:我发送两个相同的 ajax 请求,唯一的区别是一行,我如何将其包装到一个函数中以保持代码干燥?

$('.searchable').multiSelect({
selectableHeader: "<input type='text' class='search-input' autocomplete='off' placeholder='Select reservations ex. \"12\"'>",
selectionHeader: "<input type='text' class='search-input' autocomplete='off' placeholder='Remove selected reservations \"'>",
afterInit: function(ms){
var that = this,
$selectableSearch = that.$selectableUl.prev(),
$selectionSearch = that.$selectionUl.prev(),
selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',
selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected';

that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
.on('keydown', function(e){
if (e.which === 40){
that.$selectableUl.focus();
return false;
}
});

that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
.on('keydown', function(e){
if (e.which == 40){
that.$selectionUl.focus();
return false;
}
});
},
afterSelect: function(value){
$.ajax({
type: 'GET',
url: '/police/get_res_price?price=' + value,
success: function (data) {
var initial_price = parseInt($('.give-me-money').val());
var obj = JSON.parse(data);
$.each(obj, function(booking_price, value) {
initial_price += parseInt(value.BOOKING_PRICE);
});
$('.give-me-money').val(initial_price); //set total
}
});
this.qs1.cache();
this.qs2.cache();
},
afterDeselect: function(value){
$.ajax({
type: 'GET',
url: '/police/get_res_price?price=' + value,
success: function (data) {
var initial_price = parseInt($('.give-me-money').val());
var obj = JSON.parse(data);
$.each(obj, function (booking_price, value) {
initial_price -= parseInt(value.BOOKING_PRICE);
});
$('.give-me-money').val(initial_price); //set total
}
});
this.qs1.cache();
this.qs2.cache();
}
});

最佳答案

var ajaxHandler = function(decrement) {
return function(value){
$.ajax({
type: 'GET',
url: '/police/get_res_price?price=' + value,
success: function (data) {
var initial_price = parseInt($('.give-me-money').val());
var obj = JSON.parse(data);
$.each(obj, function (booking_price, value) {
if (decrement) {
initial_price -= parseInt(value.BOOKING_PRICE);
} else {
initial_price += parseInt(value.BOOKING_PRICE);
}
});
$('.give-me-money').val(initial_price); //set total
}
});
this.qs1.cache();
this.qs2.cache();
}
}

$('.searchable').multiSelect({
// other props
afterSelect: ajaxHandler(false)
afterDeselect: ajaxhander(true)
});

关于javascript - 如何在 ajax 请求中保持代码干燥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33744859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com