首页 > 解决方案 > select2 和 axios:成功不是函数

问题描述

我是 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() 函数。

标签: javascriptcallbackjquery-select2

解决方案


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

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

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

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


推荐阅读