简体   繁体   English

select2更改ajax网址

[英]select2 change ajax url

Im working with knockout.js and select2 plugin. 我正在使用knockout.js和select2插件。
Im trying to change the select2 ajax url based on a value of an observable. 我试图根据一个可观察的值更改select2 ajax网址。
for example if based on some selection i do ajax call to 1 url or another. 例如,如果基于某些选择,我执行ajax调用1 url或另一个。 Here is a sample code: 这是一个示例代码:

<input type="hidden" data-bind="combobox: { optionsText: 'Name', optionsValue: 'ID', optionsCaption: 'Избери...', sourceUrl: partnerUrl }, value: ApplyToSubject" id="ApplyToSubject" name="ApplyToSubject">

This is how the sourceUrl: partnerUrl is retrieved: 这是检索sourceUrl:partnerUrl的方式:

self.partnerUrl = ko.computed(function () {
        var value = "";
        if (something)
        {
            value = apiUrls.customer;
        }
        else if (something else)
        {
            value = apiUrls.vendor;
        }
        else if(or another thing)
        {
            value = apiUrls.employee;
        }
        return value;
    });

I work with custom binding. 我使用自定义绑定。 Here is the code for it: 这是它的代码:

// documentation http://ivaynberg.github.io/select2/
ko.bindingHandlers.combobox = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor();
        var optionsText = ko.utils.unwrapObservable(obj.optionsText);
        var optionsValue = ko.utils.unwrapObservable(obj.optionsValue);
        var sourceUrl = ko.utils.unwrapObservable(obj.sourceUrl);
        var selectedID = ko.utils.unwrapObservable(allBindings.value);
        var model = obj.model;
        var unwrapped = ko.utils.unwrapObservable(obj.model);

        $(element).select2({
            minimumInputLength: 3,
            formatResult: function formatResult(result) {
                return result.text;
            },
            data: function (model) {
                return { id: unwrapped[optionsValue](), text: unwrapped[optionsText](), data: unwrapped }
            },
            initSelection: function (element, callback) {
                if (unwrapped && selectedID !== "") {
                    callback({ id: unwrapped[optionsValue](), text: unwrapped[optionsText](), data: unwrapped });
                }
            },
            ajax: {
                quietMillis: 500,
                url: subdirUrl + sourceUrl,
                dataType: 'json',
                data: function (search, page) {
                    return {
                        page: page,
                        search: search
                    };
                },
                results: function (data) {
                    var result = [];
                    $.each(data.list, function (key, value) {
                        result.push({ id: value[optionsValue], text: value[optionsText], data: value });
                    });
                    var more = data.paging.currentPage < data.paging.pageCount;
                    return { results: result, more: more };
                }
            }
        });
        $(element).on('select2-selected', function (eventData) {
            if (eventData.choice) {
                // item selected
                var selectedItem = eventData.choice.data;
                var selectedId = eventData.choice.id;
                model(selectedItem);
            }
            else {
                model(undefined);
            }
        });

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).select2('destroy');
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor();
        var selectedID = ko.utils.unwrapObservable(allBindings.value);
        $(element).val(selectedID).trigger('change');
    }
};

It works for url's that dont change, but for urls that need to update, i cant make it work. 它适用于不改变的网址,但对于需要更新的网址,我无法使其正常工作。 (it seems like its keeping the first url that was passed (sourceUrl). (看起来它保留了传递的第一个url(sourceUrl)。

I've finally managed to solve this one. 我终于设法解决了这个问题。

From what i could read from the select2 documentation, you should pass string or function to ajax url parameter. 根据我从select2文档中读到的内容,您应该将字符串或函数传递给ajax url参数。 So this is what i've done 所以这就是我所做的
I've written a function that returns value of the observable (which is the url): 我编写了一个返回observable值(即url)的函数:

self.returnUrl = function () {
    return self.dynamicUrl();
};

And then i pass that function to my custom binding options: 然后我将该函数传递给我的自定义绑定选项:

<input data-bind="combobox: { ... sourceUrl: $data.returnUrl }, value: ApplyToSubject" type="hidden" >

Then the custom binding works the same as in the code in the question, with a small change: 然后自定义绑定的工作方式与问题中的代码相同,只需稍加改动:

...
ajax: {
     url: sourceUrl <- this is the returnUrl function
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM