jQuery Select2防止在Ajax响应中选择 [英] jquery Select2 prevent selecting in ajax response

查看:128
本文介绍了jQuery Select2防止在Ajax响应中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to prevent from adding a category to the Select2 element if it fails creating the row first in my db. The action is not prevented when i call ev.preventDefault(); Nothing happens.. what is wrong?

    $('#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(),现在也要有所作为为时已晚.因此,这为您提供了两种选择:

The AJAX request is made asynchronusly, so by the time it has finished the element has already been added. Even though you are calling ev.preventDefault(), it is too late for it to make a difference. So this leaves you with two options:

  1. 同步发出请求,这将使preventDefault有所作为.
  2. 异步发出请求,并在失败时手动删除该元素.
  1. Make the request synchronusly, which will allow preventDefault to make the difference.
  2. Make the request asynchronusly, and manually remove the element if it fails.

这两个选项各有利弊,由您决定使用哪个选项.

Both options have their pros and cons, and it's up to you to decide which option you go with.

  1. 同步发出请求

专业人士

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

缺点

  • 阻止用户界面-发出请求时,用户可能无响应的页面.
  1. 异步发出请求

专业人士

  • 不阻止UI.
  • 在通常可以添加元素的情况下效果很好.

缺点

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

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

What's important to consider here is the user experience of both options. When making synchronus requests, it's not uncommon for the browser to stop relaying events - which gives the illusion that the UI has locked up and the page has gone unresponsive. This has the benefit of ensuring that the value never shows up if it isn't allowed. But if users typically can add the elements, it also has the downside of complicating the most common use case.

如果用户通常可以添加元素,那么最好是在发出请求时添加元素,然后在出现问题时(在删除元素时)通知用户.这在Web应用程序中非常普遍,您可以看到它在很多地方都在使用,例如Twitter和Facebook之类的按钮(通常可以在其中运行请求),以及Stack Overflow上的地方.

If users can usually add elements, then it is a better experience to add the element while the request is being made, and then notifying the user later (while removing the element) if there was an issue. This is very common is web applications, and you can see it being used in many places, such as the Twitter and Facebook like buttons (where requests usually work), as well as places on Stack Overflow.

这篇关于jQuery Select2防止在Ajax响应中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆