由Javascript呼叫Webservice產生動態選單

摘要:由Javascript呼叫Webservice產生動態選單

 要做到由JavaScript呼叫Webservice的方法,並放到下拉選單的作法:
1.加入一個WebService,選擇 Web Service,檔案名稱輸入LocationService.asmx

 1.1 加入 using System.Web.Script.Services;
 1.2 為類別標上 [ScriptService] attribute:

[ScriptService()]
public class LocationService : System.Web.Services.WebService
 1.3 撰寫可供 JavaScript 呼叫的 Web 方法:
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
 1.4 撰寫取得資料庫的函式,運作JSON的結構產生陣列:

01 [WebMethod]
02 [System.Web.Script.Services.ScriptMethod]
03 public string GetCounty(string area)
04 {
05     OleDbDataReader dr = null;
06     string json = "";
07     json = "[{text:'Please Select',value:'0'},"
08     ....
09     ....
10     json += "{text:'" + dr["name"] + "',value:'" + dr["id"] + "'}
";
11     ....
12     ....
13     return json;
14 }


2.建立WebForm程式:JsCallWebService.aspx

 2.1 從工具的 AJAX Extensions 面板中拉一個 ScriptManager 控制項到網頁上,然後修改其標籤內容,如下:
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <services>
        <asp:servicereference path="~/LocationService.asmx" />
    </services>
</asp:ScriptManager>


 2.2 再拉一個DropDownList
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>


 2.3 呼叫webservice的javascript的元件或按鈕
onclick="getList('abc')"

3.建立JavaScript

01 function getList(para)
02 {
03     // 呼叫 Web service 方法。
04     MyServices.LocationService.GetCounty(para);
05 }

06
07 function pageLoad()
08 {
09     // 指定 Web service 方法呼叫完成時的預設 callback。
10     MyServices.LocationService.set_defaultSucceededCallback(methodComplete);
11 }

12
13 function methodComplete(results, context, methodName)
14 {
15     var json = "json="+results;
16     json = eval(json);
17     var obj = document.getElementById('ctl00_ContentPlaceHolder1_DropDownList1');
18     for (i = 0; i < json.length; i++) {
19         obj.options[i] = new Option(json[i].text, json[i].value);
20     }

21 }
    
參考網址:
1.http://dev.yesky.com/0/3462500.shtml
2.http://huanlin.dyndns.org/cs/blogs/huan-lins_blog/rss.aspx?Tags=AJAX&AndTags=1
3.http://tw.myblog.yahoo.com/class2u-com/article?mid=2&sc=1

網頁設計 -->找網站銀行

好站推薦:網頁設計除臭襪