简体   繁体   English

select2和axios:成功不是功能

[英]select2 and axios: success is not a function

I am new to javascript, callback functions and select2. 我是javascript,回调函数和select2的新手。 Thanks in advance for your help :) 在此先感谢您的帮助 :)

I am looking at implementing select2 to search against an API but I will have to use axios instead of the default jQuery method. 我正在考虑实现select2来搜索API,但是我将不得不使用axios而不是默认的jQuery方法。 Below is my code. 下面是我的代码。 I am able to send and retrieve results but I am not sure how to use the success callback. 我能够发送和检索结果,但是我不确定如何使用成功回调。

I get "TypeError: success is not a function" 我收到“ 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
});

Questions 问题

  1. How do I return the response data to processResults in the .then function on the axios request? 如何在axios请求的.then函数中将响应数据返回到processResults? The documentation is at https://select2.org/data-sources/ajax 该文档位于https://select2.org/data-sources/ajax
  2. What is the best way to pass the input from the select list to the post request? 将输入从选择列表传递到发布请求的最佳方法是什么? Currently I am using jQuery.val() function which doesn't seem to work. 目前,我正在使用似乎无法正常工作的jQuery.val()函数。

You can create callback functions just like any other functions. 您可以像创建其他任何函数一样创建回调函数。 For example: 例如:

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

Callback means that you pass this function as parameter for later execution. 回调意味着您将此函数作为参数传递给以后执行。

When you create select2 ajax transport, then you pass your function name as parameter (as callback function). 创建select2 ajax传输时,然后将函数名称作为参数(作为回调函数)传递。 When code execution meets line "success(response);" 当代码执行遇到行“ success(response);”时 then your success function is actually executed. 那么您的成功函数实际上就会执行。

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

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