我试图根据第一个选择框中的选择填充一个选择框.我在网上看了一下,发现了很多关于硬编码选项的有用信息,但我需要我的选项来自查询(比如coldfusion中的cfquery).我知道cfquery是服务器端的,所以我不能将它包含在我的jquery中,但还有其他选择吗?
我使用以下示例:
HTML:
<select id="counties">
<option> </option>
<option> somerset </option>
<option> hertfordshire </option>
</select>
<select id="towns" disabled="true">
</select>
Run Code Online (Sandbox Code Playgroud)
JS:
var countyTowns = [
["Bath", "Bristol"],
["Letchworth", "Hitchin"]
];
$("#counties").change(function() {
var county = this.selectedIndex - 1;
$("#towns").empty();
if (county === -1) {
$("#towns").attr("disabled", true);
} else {
var towns = countyTowns[county];
for (var i = 0; i < towns.length; i++) {
$("#towns").append($("<option></option>").text(towns[i]));
}
$("#towns").attr("disabled", false);
}
});
Run Code Online (Sandbox Code Playgroud)
我需要的是城镇是动态的,能够从数据库中读取.
任何帮助是极大的赞赏!
谢谢
Edg*_*ado 12
这里有一些例子:
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html(也许是最好的,从这里开始)
http://blog.chapagain.com.np/using-jquery-ajax-populate-selection-list/
正如您提到的:城镇是动态的,并且能够从数据库中读取,您可以通过使用ajax传递来获取动态数据。
Ajax 从控制器获取以从用户选择的基于国家/地区的数据库中读取:
<script>
$(document).ready(function () {
$("#counties").on('change', function () {
var selectedItem = $(this).val();
var ddlStates = $("#towns"); // will be update after success ajax call
var statesProgress = $("#states-loading-progress");
statesProgress.show();
$.ajax({ // get states/towns from db from controller
cache: false,
type: "GET",
url: "@(Url.RouteUrl("GetStatesByCountryId"))",
data: { "countryId": selectedItem, "addSelectStateItem": "true" },
success: function (data) {
ddlStates.html('');
$.each(data, function (id, option) {
ddlStates.append($('<option></option>').val(option.id).html(option.name));
}); // populating result
statesProgress.hide(); // hide loader
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve states.');
statesProgress.hide();
}
});
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
在控制器上:
public virtual IActionResult GetStatesByCountryId(string countryId, bool addSelectStateItem)
{
var model = _countryModelFactory.GetStatesByCountryId(countryId, addSelectStateItem);
return Json(model);
}
Run Code Online (Sandbox Code Playgroud)
然后在数据访问层 上,我根据国家/城镇用户选择的数据库从数据库_countryModelFactory.GetStatesByCountryId()获取城镇/州。
更新:
这是我从数据库(动态国家/城镇)检索州/城镇并将其填充到我的代码中的方式selectbox。
| 归档时间: |
|
| 查看次数: |
47747 次 |
| 最近记录: |