【发布时间】:2016-08-12 00:23:28
【问题描述】:
我在我的网络应用程序中使用 Select2。我用 Ajax 加载我的 Select2 框。当验证失败时,除了 Select2 框外,所有输入都像以前一样填充。表单验证失败后如何恢复旧值?我的赌注是使用Request::old('x'),但这会插入值(在我的情况下是用户 ID)而不是选定的文本。例如,文本John 将在选择框中变为27。我怎样才能找回文字?
<select id="customer" name="customer" class="searchselect searchselectstyle">
</select>
js:
token = '{{csrf_token()}}';
$(".searchselect").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
return {
term: params.term,
'_token': token,
'data' : function(){
var result = [];
var i = 1;
$('.searchselect').each(function(){
result[i] = $(this).val();
i++;
});
return result;
}
};
},
url: function() {
var type = $(this).attr('id');
return '/get' + type;
},
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
编辑
到目前为止,我发现的唯一(肮脏)解决方案如下:
<select id="customer" name="customer" class="searchselect searchselectstyle">
@if(Request::old('customer') != NULL)
<option value="{{Request::old('customer')}}">{{$customers->where('id', intval(Request::old('customer')))->first()->name}}</option>
@endif
</select>
$customers 是所有客户的列表,因此这意味着对于每个 Select2 框,我需要查询一个大的项目列表才能使其正常工作。如果我们谈论的是每个 Select2 框有数千行,这将是非常低效的。
我想一定有更好的解决方案。谁能帮帮我?
【问题讨论】:
标签: ajax laravel laravel-5 jquery-select2