Ker*_*y82 3 javascript ruby-on-rails jquery-select2 jquery-select2-4
我在 Rails 中使用 select2 和 gem Rails-select2,目前使用 4.0.3 版本。
我无法使 select2 的 ajax 版本工作,我将数据设置为数组的静态版本正在工作,而 ajax 版本则不然。
我没有收到任何错误,后端也没有 ajax 调用。
选择以 select2 样式显示为空,当我键入时,它不执行任何操作。
有没有办法调试或了解问题出在哪里?
我正在使用以下示例代码:
论观点:
<select class="js-data-example-ajax" style="width:100%">
<option value="3620194" selected="selected">Select a value......</option>
</select>
Run Code Online (Sandbox Code Playgroud)
在 JavaScript 上:
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
}
});
Run Code Online (Sandbox Code Playgroud)
javascript 控制台上没有错误,如果我使用数组数据,一切正常(所以我猜 select2 导入没有问题)。
我需要找到一种方法来更好地调试问题,以正确理解问题所在。
小智 6
我不知道为什么这个例子不起作用,但也许这个代码片段适合你select2在rails. 我用过gem 'select2-rails', '4.0.3'和gem 'rails', '~> 5.0.0'
将其添加到 .js 文件中并进行更改
html selector和url选项
document.addEventListener("turbolinks:load", function(){
if ($(".select-vehicle")) {
$(".select-vehicle").select2({
theme: 'bootstrap',
allowClear: true,
minimumInputLength: 1,
dataType: 'json',
ajax: {
url: '/admin/vehicles/search',
delay: 250,
data: function(params) {
return { vin: params.term }
},
processResults: function (data, params) {
return {
results: $.map(data, function(value, index){
return {id: value.id, text: value.vin};
})
};
cache: true
}
}
});
}
})
Run Code Online (Sandbox Code Playgroud)
这是在VehicleController中搜索车辆的方法
def search
if params[:vin].present?
vehicles = Vehicle.where("vin LIKE ?", "%#{params[:vin]}%")
render json: vehicles.map{|v| v.serializable_hash(only: [:id, :vin]) }
else
render json: []
end
end
Run Code Online (Sandbox Code Playgroud)
这是 select2 的一个简单实现,告诉我它是否有用。
| 归档时间: |
|
| 查看次数: |
2630 次 |
| 最近记录: |