成功时select2检索新创建的标签ID

时间:2014-08-05 23:42:21

标签: php jquery ajax jquery-select2

在select2中我有AJAX加载的标签,如果在db中找不到标签,那么用户可以选择创建一个新标签。问题是新标签在select2框中列为一个术语,而不是作为id(选择想要什么 - 如果用户想要更新,则再次加载标签时会出现问题,因为只有术语而不是id存储在db)中。 如果成功添加该字词,我怎样才能使select2接收ID并提交ID而不是标记名称/术语?

$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
    multiple: true,
    placeholder: "Please enter tags",
    tokenSeparators: [","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "framework/helpers/tags.php",
        dataType: "json",
        data: function(term) {
            return {
                term: term
            };
        },
        results: function(data) {
            return {
                results: data
            };
        }
    },
    createSearchChoice: function(term) {
        var text = term + (lastResults.some(function(r) {
            return r.text == term
        }) ? "" : " (new)");
        return {
            id: term,
            text: text
        };
    },
});
$('#project_tags').on("change", function(e) {
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {
            var response = confirm("Do you want to add the new tag " + e.added.id + "?");
            if (response == true) {
                alert("Will now send new tag to server: " + e.added.id);
                $.ajax({
                    url: 'framework/helpers/tags.php',
                    data: {
                        action: 'add',
                        term: e.added.id
                    },
                    success: function(data) {

                    },
                    error: function() {
                        alert("error");
                    }
                });
            } else {
                console.log("Removing the tag");
                var selectedTags = $("#project_tags").select2("val");
                var index = selectedTags.indexOf(e.added.id);
                selectedTags.splice(index, 1);
                if (selectedTags.length == 0) {
                    $("#project_tags").select2("val", "");
                } else {
                    $("#project_tags").select2("val", selectedTags);
                }
            }
        }
    }
});

});

这是执行添加的开关的一部分

case 'add':
    if (isset($_GET['term'])) {
        $new_tag = escape($_GET['term']);
        if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
            // we need to send back the ID for the newly created tag
            $search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
            list($tag_id) = $search->fetch_row();
            echo $tag_id;
        } else {
            echo 'Failure';
        }
        exit();
    }
    break;

更新:我已经做了一些挖掘,让我感到困惑的是,select2输入似乎没有存储标签/术语的相关ID(见下文)。我知道我可以通过成功回调更改属性,但我不知道要改变什么!

enter image description here

1 个答案:

答案 0 :(得分:4)

正如您所说,您可以替换该值,这就是我的解决方案所做的。如果您搜索Chrome的元素检查器,则会在Select2字段旁边看到一个标识为project_tagsheight1的输入。

奇怪的是Chrome的元素检查器没有显示输入的值,如下所示:

enter image description here

但是,您输入的值为console.log($("#project_tags").val())(如图所示)。

因此,您可以在success函数中放置的ajax调用的$('#project_tags').on("change")函数内,用id替换新选项的文本。 ajax电话会是:

$.ajax({
    url: 'framework/helpers/tags.php',
    data: {
        action: 'add',
        term: e.added.id
    },
    success: function(tag_id) {
        var new_val = $("#project_tags")
                        .val()
                        .replace(e.added.id, tag_id);
        $("#project_tags").val(new_val);
    },
    error: function() {
        alert("error");
    }
});

请注意,此解决方案不是防弹。例如,如果您选择了值为1的标记,并且用户插入了文本1,则会导致问题。

也许更好的选择是替换最后一个逗号右边的所有内容。但是,如果允许用户使用逗号创建标记,即使这可能会导致一些问题。

如果您需要更多信息,请与我们联系。

相关问题