gpt4 book ai didi

javascript - jquery Select2 防止在 ajax 响应中选择

转载 作者:搜寻专家 更新时间:2023-11-01 04:54:13 28 4
gpt4 key购买 nike

如果无法在我的数据库中首先创建行,我想阻止向 Select2 元素添加类别。当我调用 ev.preventDefault() 时不会阻止该操作;什么都没发生.. 怎么了?

    $('#sel2').select2({
placeholder: 'Enter categories',
minimumInputLength: 3,
multiple: true,
ajax: {
url: 'async/get_categories.php',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
q: term,
};
},
results: function (data, page) {
return {
results: data.items
};
},
cache: true
},
formatResult: format,
formatSelection: format
}).on('select2-selecting', function(e) {
console.log(e);
if (e.val == 4) {
// if category id equals 4
// do not add this category to select 2
// e.preventDefault();
// the above works just fine and its just for testing
}

// Is something wrong here?
var ev = e;

$.ajax({
type: 'POST',
url: 'async/create_profile_category.php',
data: {
profile_id: '1',
category_id: ev.val
},
success: function(response) {
console.log(response);
if (response.error === false) {
// category assigned successfully
} else {
// failed to assign category
// so i want now to prevent from adding to select2
console.log('should not add this category');
ev.preventDefault();
// the above is not working
}
},
error: function() {
alert('Failed to assign category!');
}
});
});

最佳答案

AJAX 请求是异步发出的,所以当它完成时,元素已经被添加。即使您正在调用 ev.preventDefault(),它也为时已晚,无法发挥作用。因此,您有两个选择:

  1. 同步发出请求,这将允许 preventDefault 发挥作用。
  2. 异步发起请求,失败时手动移除元素。

这两种选择各有利弊,由您决定选择哪种方式。


  1. 同步发出请求

优点

  • 如果请求失败,则永远不会添加该值。
  • 在不能经常添加元素的情况下效果很好。

缺点

  • 阻止 UI - 因此在发出请求时用户可能会看到无响应的页面。

  1. 异步发出请求

优点

  • 不阻塞用户界面。
  • 在通常可以添加元素的情况下效果很好。

缺点

  • 该值将始终为用户显示,即使稍后失败。
  • 您必须手动取消设置新选项。

这里重要的是要考虑这两个选项的用户体验。发出同步请求时,浏览器停止中继事件的情况并不少见——这给人一种 UI 已锁定且页面无响应的错觉。这样做的好处是确保该值在不允许的情况下永远不会出现。但是,如果用户通常可以添加元素,那么它也有使最常见的用例复杂化的缺点。

如果用户通常可以添加元素,那么最好在发出请求时添加元素,然后在出现问题时通知用户(同时删除元素)。这在 Web 应用程序中很常见,您可以在很多地方看到它的使用,例如 Twitter 和 Facebook 之类的按钮(请求通常在此处起作用),以及 Stack Overflow 上的地方。

关于javascript - jquery Select2 防止在 ajax 响应中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705098/

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