我有以下代码:
<hr class="col-sm-10"/>
<form class="col-sm-10 form-horizontal">
<div class="form-group">
<label for="test" class="control-label col-sm-2">Name</label>
<div class="col-sm-10">
<select class="col-sm-10 form-control" id="tenantList">
</select>
</div>
</div>
</form>
<script>
var tenants = [];
$.ajax({
url: 'api/Tenant'
})
.done(function (data) {
tenants = data;
})
.fail(function () {
console.log("Problem :(");
});
$('#tenantList').select2({
placeholder: "Select a tenant",
allowClear: true,
data: tenants
});
</script>
租户变量未设置为返回的JSON数组。数据来自Server成功,但变量仍为空。我究竟做错了什么?在Select2中这样做的正确方法是什么?
答案 0 :(得分:0)
在select ajax中移动select2指令
<hr class="col-sm-10"/>
<form class="col-sm-10 form-horizontal">
<div class="form-group">
<label for="test" class="control-label col-sm-2">Name</label>
<div class="col-sm-10">
<select class="col-sm-10 form-control" id="tenantList">
</select>
</div>
</div>
</form>
<script>
var tenants = [];
$.ajax({
url: 'api/Tenant'
})
.done(function (data) {
tenants = data;
$('#tenantList').select2({
placeholder: "Select a tenant",
allowClear: true,
data: tenants
});
})
.fail(function () {
console.log("Problem :(");
});
</script>
答案 1 :(得分:0)
获取数据后,您需要将返回的数据从ajax分配给select2的“data”:
function callajax() {
$.ajax({
url: 'api/Tenant'
})
.done(function(data) {
$('#tenantList').select2({
placeholder: "Select a tenant",
width: "200px",
allowClear: true,
data: data
});
})
.fail(function() {
console.log("Problem :(");
});
}
callajax();
希望有所帮助