选择我会定义一个 WCF 服务,该服务使用内置的集合数据协定之一来呈现 JSON 中的列表:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class optionsservice
{
// Return a dynamic list of the options
[WebInvoke(UriTemplate = "/getOptions?type={type}", Method = "GET", ResponseFormat = WebMessageFormatJson)]
public SelectOptions getOptions(string filter = "")
{
SelectOptions returnOptions = new SelectOptions();
//get your datatable here.
foreach (DataRow r in tbl.Rows)
{
returnOptions.Add((string)r["id"], (string)r["value"]);
}
return returnOptions;
}
[CollectionDataContract(Name = "collection",
KeyName = "id",
ValueName = "value",
Namespace = "")]
public class SelectOptions : Dictionary<string, string> { }
}
您也可以将数据表转换为列表,但这是我手头上唯一的示例代码
下面是你如何将盒子加载到 jQuery 中:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
$("select#ctlSelect").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i]value + '</option>';
}
$("select#ctlSelect").html(options);
})
})
})
</script>