我正在尝试使用jquery ajax根据国家/地区选择绑定状态,而我只使用html select for states。
<select id="State" class="selectpicker" required>
</select>
@Html.DropDownList("Countries", (IEnumerable<SelectListItem>)ViewBag.CountryId, "Select", new { @class = "selectpicker", @readonly = "true" })
$('#Countries').on('change', function () {
var CountryId = $('#Countries').val();
$.ajax({
url: "/Home/GetStates",
data: JSON.stringify({
CountryId: CountryId
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (Result) {
$.each(Result, function (item,index) {
console.log(index);
$.each(index, function (i) {
//$('#State').append($("<option></option>")
// .attr("value", index[i].StateID)
// .text(index[i].StateName));
//$('#State').append($('<option>', {
// value: index[i].StateID,
// text: index[i].StateName
//}, '</option>'));
var optionhtml = '<option value="' +index[i].StateID + '">' + index[i].StateName + '</option>';
console.log(optionhtml);
$("#State").append(optionhtml);
//$("#State").append($("<option></option>").text(index[i].StateName).val(index[i].StateID));
});
});
error: function (request, status, error) {
alert("error occured -- "+request.responseText);
}
});
});
问题只是数据没有显示为选项。我使用不同的方式循环我的结果并创建我的选择id = State。 (这些在上面的代码中评论)
答案 0 :(得分:0)
请参阅有关现有代码的评论。
$.each(index, function (i) {
//$('#State').append($("<option></option>")
// .attr("value", index[i].StateID)
// .text(index[i].StateName));
//$('#State').append($('<option>', {
// value: index[i].StateID,
// text: index[i].StateName
//}, '</option>'));
var optionhtml = '<option value="' +index[i].StateID + '">' + index[i].StateName + '</option>'; //this creates new variable for each item
console.log(optionhtml);
$("#State").append(optionhtml); // current item will be appended. Also this needs to be replaced
//$("#State").append($("<option></option>").text(index[i].StateName).val(index[i].StateID));
});
将$ optionhtml放在$ .each之前。
替换
var optionhtml = '<option value="' +index[i].StateID + '">' + index[i].StateName + '</option>';
用这个
optionhtml += '<option value="' +index[i].StateID + '">' + index[i].StateName + '</option>';
$("#State").append(optionhtml); // needs to be placed after $.each ends
答案 1 :(得分:0)
<select class="selectpicker"></select>
似乎您正在使用bootstrap,因此要以编程方式使用JavaScript更新select,首先操作select,然后使用refresh方法更新UI以匹配新状态。在删除或添加选项时,或通过JavaScript禁用/启用选择时,这是必需的。
use this:
$("#State").append(optionhtml).selectpicker('refresh');