select2和axios:成功不是功能

时间:2018-11-14 03:56:19

标签: javascript callback jquery-select2

我是javascript,回调函数和select2的新手。预先感谢您的帮助:)

我正在考虑实现select2来搜索API,但我将不得不使用axios而不是默认的jQuery方法。下面是我的代码。我可以发送和检索结果,但是我不确定如何使用成功回调。

我得到“ TypeError:成功不是函数”

$("#profile-select").select2({
    ajax: {
        transport: function(params, success, failure){
        axios.post("/rest/vue/1.0/profile/search", {query: $("#profile-select").val()})
        .then(function(response){
           success(response);
        })
        .catch(function(error){
           alert(error);
        });
    },
    processResults: function(data){
        var processedArray = [];
        data.profiles.forEach(function(item){
            processedArray.push({id: item.ID, text: item.name});
        });
        return processedArray;
        }
    },
    minimumInputLength: 2,
    placeholder: "Select a profile",
    allowClear: true
});

问题

  1. 如何在axios请求的.then函数中将响应数据返回到processResults?该文档位于https://select2.org/data-sources/ajax
  2. 将输入从选择列表传递到发布请求的最佳方法是什么?目前,我正在使用似乎无法正常工作的jQuery.val()函数。

1 个答案:

答案 0 :(得分:0)

您可以像创建其他任何函数一样创建回调函数。 例如:

function success(response) {
  //do with response data what's necessary
}

回调意味着您将此函数作为参数传递给以后执行。

创建select2 ajax传输时,然后将函数名称作为参数传递(作为回调函数)。 当代码执行遇到行“ success(response);”时那么您的成功函数就会被实际执行。