新建WebService
[System.Web.Script.Services.ScriptService]//前台调用方法需要加入这句话
[WebMethod]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<GWInfo> GetGwName(string prefix)
{
List<GWInfo> persons = new List<GWInfo>();
GWInfo a = new GWInfo();
a.dep = prefix;
foreach (GWInfo g in GW.GetGWByA(a))
{
persons.Add(g);
}
return persons;
}
前台,使用JQuery的Ajax调用WebService内方法
引用jq库
<script src="../JQuery/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#<%= DropDownList1.ClientID %>").change(function () {
// $.getJSON(
// "JsonText.txt",
// function (JsonData) {
// $.each(JsonData.employees, function (i, item) {
// $("<option value='" + item.firstName + "'>" + item.firstName + "</option>").appendTo("#<%= DropDownList2.ClientID %>");
// })
// })
$.ajax({
url: '<%=ResolveUrl("~/Test/GetAuto.asmx/GetGwName") %>',
data: "{ 'prefix': '" + $(this).val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (JsonData) {
$("#<%= DropDownList2.ClientID %>").empty();
$(JsonData.d).each(function () {
$("<option value='" + this.name + "'>" + this.name + "</option>").appendTo("#<%= DropDownList2.ClientID %>");
})
}
});
});
});
</script>
注释的方法是Ajax调用Json,JsonText.txt文本内容(Json格式)
{
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
}
<div>
部门:<asp:DropDownList runat ="server" ID ="DropDownList1" Width ="120px">
<asp:ListItem Value ="">--选择--</asp:ListItem>
<asp:ListItem Value ="IT">IT</asp:ListItem>
<asp:ListItem Value ="财务">财务</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList runat ="server" ID ="DropDownList2" Width ="120px"></asp:DropDownList>
</div>