How to pass selected value as extra parameter to ajax call

跟風遠走 提交于 2019-12-11 04:35:15

问题


my coding part

$("#demo-input").tokenInput("data/autosuggest-search-city.php", 
        {
            searchDelay: 2000,
            minChars: 3,
            tokenLimit: 10
        });

I want to send the selected values as extra parameter to "data/autosuggest-search-city.php".

For example, Initially I search and select one value from list then again searching, this time I want to send the 1st selected value to server.

How to do this?


回答1:


TokenInput plugin doesn't support that natively.
You can however make a simple workaround to update "AJAX url" whenever a token is added or removed from selection.

Use onAdd and onDelete callbacks to trigger "AJAX url" changes;
Get selected tokens using selector.tokenInput("get") method;
Set the new "AJAX url" by updating .data("settings").url of the element;

// cache the original url:
var token_url = "data/autosuggest-search-city.php";

$("#demo-input").tokenInput(token_url, {
    searchDelay : 2000,
    minChars    : 3,
    tokenLimit  : 10,
    onAdd       : function(){
        urlChange.call(this);
    },
    onDelete    : function(){
        urlChange.call(this);
    }
});

function urlChange(){
    var tokens = '', token_list = $(this).tokenInput("get");
    // proceed if any token/s are selected:
    if(token_list.length){
        // loop through the selected tokens (if more than one is selected)
        $.each(token_list, function(i, token){
            // use token "id" (or "name" if you wish) and separate them with comma:
            tokens += token.id + ',';
        });
        // update url:
        $(this).data("settings").url = token_url + '?selected_tokens='+tokens.replace(/,+$/,'');
    }else{
        // leave original url if no tokens are selected:
        $(this).data("settings").url = token_url;
    }
};


来源:https://stackoverflow.com/questions/30938988/how-to-pass-selected-value-as-extra-parameter-to-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!