javascript - 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
});
问题
- 如何在axios请求的.then函数中将响应数据返回给processResults?该文档位于https://select2.org/data-sources/ajax
- 将输入从选择列表传递到发布请求的最佳方式是什么?目前我正在使用似乎不起作用的 jQuery.val() 函数。
解决方案
您可以像创建任何其他函数一样创建回调函数。例如:
function success(response) {
//do with response data what's necessary
}
回调意味着您将此函数作为参数传递给以后执行。
当您创建 select2 ajax 传输时,您将函数名称作为参数(作为回调函数)传递。当代码执行遇到“success(response);”行时 然后你的成功函数实际上被执行了。
推荐阅读
- azure-data-factory - Azure 数据工厂存储事件触发器 - 身份验证
- c++ - pthread_create() 似乎泄漏内存
- python - 我希望这段代码在现有的 xlsx 中创建一个新工作表,而不是创建一个新文件
- powerquery - Power Query - 如何在分隔符后提取
- python - Python“in”语句是循环吗?
- css - CSS 动画在 Safari / 所有 iPhone 浏览器上表现不同
- html - req.body 对于表单 GET 请求为空
- javascript - Google 柱形图中的结果不正确
- android - Kotlin:如何在 Fragment 中打开一个新的 Activity
- java - 为什么 Collections 参数中的 unmodifiableList 是